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

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 files = FileUtils.listFiles(file, null, false);

// This works

File file2 = new File ("C:\\test");

Collection 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.

解决方案

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值