以下方法用于设置FTP连接的传输类型。基本上,我想验证字符输入(见注释)。
这是否过分了?有更优雅的方法吗?您如何处理参数验证?欢迎提出任何意见。
public void setTransferType(Character typeCharacter,
Character optionalSecondCharacter) throws NumberFormatException,
IOException {
// http://www.nsftools.com/tips/RawFTP.htm#TYPE
// Syntax: TYPE type-character [second-type-character]
//
// Sets the type of file to be transferred. type-character can be any
// of:
//
// * A - ASCII text
// * E - EBCDIC text
// * I - image (binary data)
// * L - local format
//
// For A and E, the second-type-character specifies how the text should
// be interpreted. It can be:
//
// * N - Non-print (not destined for printing). This is the default if
// second-type-character is omitted.
// * T - Telnet format control (<CR>, <FF>, etc.)
// * C - ASA Carriage Control
//
// For L, the second-type-character specifies the number of bits per
// byte on the local system, and may not be omitted.
final Set<Character> acceptedTypeCharacters = new HashSet<Character>(Arrays.asList(
new Character[] {'A','E','I','L'}
));
final Set<Character> acceptedOptionalSecondCharacters = new HashSet<Character>(Arrays.asList(
new Character[] {'N','T','C'}
));
if( acceptedTypeCharacters.contains(typeCharacter) ) {
if( new Character('A').equals( typeCharacter ) || new Character('E').equals( typeCharacter ) ){
if( acceptedOptionalSecondCharacters.contains(optionalSecondCharacter) ) {
executeCommand("TYPE " + typeCharacter + " " + optionalSecondCharacter );
}
} else {
executeCommand("TYPE " + typeCharacter );
}
}
}
答案 0 :(得分:2)
在一个简单的正则表达式检查中验证整个字符串:
String.matches("TYPE ([AE] [NTC]|I|L .)")
(注意我在L之后使用了“。”(任何字符),因为doc没有解释该字符应该是什么。如果它只能是7或8,请使用[78]。)
你可以更进一步(捕获组,预编译正则表达式,允许任意额外的空格等),但上面基本上是这样做的。
答案 1 :(得分:1)
以下是我的意思:
private static final List<String> ALLOWED = Arrays.asList("AN", "AT", "AC", "EN", "ET", "EC");
public void setTransferType(Character type, Character optional)
throws NumberFormatException, IOException {
String[] arr = new String[] { "AN", "AT", "AC", "EN", "ET", "EC" };
if(type = 'I')
executeCommand("TYPE " + type );
else if(type = 'L') {
executeCommand("TYPE " + type + " " + optional);
else if(ALLOWED.contains("" + type + optional))
executeCommand("TYPE " + type + " " + optional);
else
// Handle an incorrect argument error
}
executeCommand("TYPE " + type + " " + optional);
else
(最后一个)来明确处理这种情况。 typeCharacter
。名称的'Character`后缀是噪音 - 它不会添加任何有用的信息。