以下方法用于设置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 );
}
}
}
最佳答案
通过一次简单的正则表达式检查验证整个字符串:
String.matches("TYPE ([AE] [NTC]|I|L .)")
(请注意,我在 L 之后使用了“.”(任何字符),因为文档没有解释该字符应该是什么。如果它只能是 7 或 8,请使用 [78]。)
您可以更进一步(捕获组、预编译正则表达式、允许任意额外的空格等),但上面的内容基本上做到了。
关于java - 根据固定引用验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3030068/