簡體   English   中英

如何在Java中的命令行參數(文件路徑)中轉義斜線?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM