【问题标题】:Java - taking multiple paths as command line arguments whitespace issueJava - 将多个路径作为命令行参数空格问题
【发布时间】:2013-08-21 18:42:06
【问题描述】:

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

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”的一部分?

【问题讨论】:

  • 用引号将路径括起来。
  • 您是否尝试将路径用引号括起来?

标签: java command-line path whitespace


【解决方案1】:

使用引号:

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

【讨论】:

    【解决方案2】:

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

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

    这样你就可以比较它们了。

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2015-02-20
      • 1970-01-01
      • 2014-04-12
      • 2012-09-24
      • 2017-09-19
      • 2011-10-24
      • 1970-01-01
      • 2013-06-03
      相关资源
      最近更新 更多