[英]How to escape slashes in command line argument (file path) in Java?
请注意,我正在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遍历每个文件?
非常感谢您的帮助。
更换您的替代品
escaped = inputDirectory.replaceAll("\\", "\\\\");
至
escaped = inputDirectory.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));
由于您在程序中模仿参数,因此请考虑到
"-i C:\test"
实际上将是C:
和est
之间的tab
(即\\ t)
正确的方法是:
"-i C:\\test"
但老实说,我不知道如何将其应用于命令行参数。
如果您的问题是如何传递命令行参数,则可以在Windows命令提示符下使用java命令,如下所示。
cmd> java Test C:\test1
或者,如果您想在项目属性下的netbeans中传递参数,请运行,然后在参数字段中添加每个参数,如下所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.