有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中转义命令行参数(文件路径)中的斜杠?

请注意,我是在Windows下使用NetBeans开发的。我还运行JDK1.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,但正如它在代码中所说的,它没有编译,并且返回了一个无效的正则表达式错误

我知道最好的做法是使用文件。分隔符,但我真的不知道如何将其应用于命令行参数。用户可能会键入一个相对路径。用户引用的文件路径也可以位于任何驱动器上

如何避开反斜杠,以便使用FileUtils循环遍历每个文件

非常感谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    but I honestly have no clue how I can apply it to a command line argument.

    如果您的问题是如何传递命令行参数,您可以在windows命令提示符中使用java命令,如下所示

    cmd> java Test C:\test1
    

    或者,如果要在项目属性下的netbeans中传递参数->;跑 然后在arguments字段中添加每个参数,如下所示

    How to pass arguments

  2. # 2 楼答案

    更换替代者

    escaped = inputDirectory.replaceAll("\\", "\\\\");
    

    escaped = inputDirectory.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));
    

    由于您是在程序中模拟参数,请考虑这一点

     "-i C:\test"
    

    实际上将是介于{}和{}之间的{}(即\t)

    正确的方法应该是:

     "-i C:\\test"