【发布时间】:2015-06-13 21:49:22
【问题描述】:
请注意,我在 Windows 下使用 NetBeans 进行开发。我也在运行 JDK 1.8。
程序通过命令行接受一些参数。一个参数是文件路径。用户可以键入-i C:\test。我如何逃脱斜线?似乎没有什么工作正常。
public class Test {
public static void main(String[] args) throws FileNotFoundException, ParseException {
// Simulate command line execution
String[] arguments = new String[] { "-i C:\test" };
// Create Options object
Options options = new Options();
// Add options input directory path.
options.addOption("i", "input", true, "Specify the input directory path");
// Create the parser
CommandLineParser parser = new GnuParser();
// Parse the command line
CommandLine cmd = parser.parse(options, arguments);
String inputDirectory = cmd.getOptionValue("i");
String escaped;
// Gives error of "invalid regular expression: Unexpected internal error
escaped = inputDirectory.replaceAll("\\", "\\\\");
// This does not work
File file = new File (escaped);
Collection<File> files = FileUtils.listFiles(file, null, false);
// This works
File file2 = new File ("C:\\test");
Collection<File> files2 = FileUtils.listFiles(file2, null, false);
}
}
我尝试了 replaceAll,但就像代码中所说的那样,它无法编译并且返回一个无效的正则表达式错误。
我知道最佳实践是使用 File.separator,但老实说,我不知道如何将它应用于命令行参数。也许用户可能会键入一个相对路径。用户引用的文件路径也可以在任何驱动器上。
如何转义反斜杠以便我可以使用 FileUtils 遍历每个文件?
非常感谢您的帮助。
【问题讨论】:
-
仅供参考,正斜杠 (
/) 仅适用于 Java,例如new File("C:/dir/foo")
标签: java command-line escaping command-line-arguments slash