有 Java 编程相关的问题?

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

Java将多个路径作为命令行参数空格问题

假设我想在命令行上传递以下路径:

Path a: C:\example a\test
Path b: C:\example b\test\

java -jar myjar.jar C:\example a\test C:\example b\test\

Java使用空格分割参数,因此我们将得到一个args数组,如下所示:

arr[0] = C:\example
arr[1] = a\test
arr[2] = C:\example
arr[3] = b\test\

但是如果我们还希望接受非绝对路径,那么提供“\test”将导致程序将其接受为<parent directory>\test

这会带来很多问题,而且比最初看起来要复杂得多。我们如何告诉Java“a\test”实际上是“C:\example a\test”的一部分,而不是“<parent directory>\a\test


共 (2) 个答案

  1. # 1 楼答案

    创建规范文件并从中提取绝对名称:

    try {
        File file = (new File(arr[0])).getCanonicalFile();
        arr[0] = file.getAbsolutePath();
    
    } catch (IOException e) {
        // handle exception
    }
    

    这样你可以比较它们

  2. # 2 楼答案

    使用引号:

    java -jar myjar.jar "C:\example a\test" "C:\example b\test\"