How to escape slashes in command line argument (file path) in Java?

妖精的绣舞 提交于 2019-12-11 12:17:23

问题


Please note I'm developing this using NetBeans under Windows. I'm also running JDK 1.8.

The program takes a few arguments, via the command-line. One argument is a file path. The user might type -i C:\test. How do I escape the slash? Nothing seems to work right.

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);
    }
}

I tried replaceAll but, like it says in the code, it does not compile and it returns an invalid regular expression error.

I know best practice is to use File.separator, but I honestly have no clue how I can apply it to a command line argument. Maybe the user might type a relative path. The file path the user references could be on any drive, as well.

How do I escape the backslashes so that I can loop through each file with FileUtils?

Thank you very much for any help.


回答1:


Change your replacement

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

to

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

Since you are mimicking the argument within your program, take in account that

 "-i C:\test"

Will actually be a tab (i.e \t) in between C: and est

the correct way would've been:

 "-i C:\\test"



回答2:


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

If your problem is how to pass command line arguments, You may either use java command in windows command prompt as follows.

cmd> java Test C:\test1

Or if you want to pass arguments in netbeans under project properties -> run and then add each parameters in arguments field as shown below.



来源:https://stackoverflow.com/questions/29523089/how-to-escape-slashes-in-command-line-argument-file-path-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!