简体   繁体   English

无法在文件中使用类路径运行 java 程序,并且在 cli 上使用 @

[英]Unable to run java program with a classpath in a file and usage of @ on the cli

I came across a strange behavior when executing a java program from command line with a classpath in a file.从命令行使用文件中的类路径执行 java 程序时,我遇到了一个奇怪的行为。 I'm not sure if this is related to Windows, Java or the cli.我不确定这是否与 Windows、Java 或 cli 有关。

Test class:测试类:

package de.test;

public class Playground {

    public static void main(String[] args) throws Exception {
        System.out.println("hello world");
    }

}

After compiling I can run it with the command编译后我可以用命令运行它

java -classpath "C:\Users\TEST\eclipse-workspace\Playground\target\classes" de.test.Playground

However, if I have a file cp.txt with the content (this is only the classpath argument)但是,如果我有一个包含内容的文件cp.txt (这只是类路径参数)

-classpath "C:\Users\TEST\eclipse-workspace\Playground\target\classes"

and I run我跑

java "@cp.txt" de.test.Playground

I get the error java.lang.ClassNotFoundException: de.test.Playground .我收到错误java.lang.ClassNotFoundException: de.test.Playground Same without quotes around @cp.txt .同样没有@cp.txt周围的引号。

I tested this with Oracle JDK 11.0.2 and OpenJDK 11.0.5.我使用 Oracle JDK 11.0.2 和 OpenJDK 11.0.5 对此进行了测试。 Both show the same behavior.两者都表现出相同的行为。

Does anyone know why this happens?有谁知道为什么会这样? Whenever the classpath is too long, Eclipse puts it in a file and uses the @ command line to run the program.每当类路径太长时,Eclipse 就会将其放入一个文件中,并使用@ 命令行来运行程序。 But this doesn't work as shown above.但这不起作用,如上所示。 So whenever I have too many dependencies I'm no longer able to run a Java program from within Eclipse.因此,每当我有太多依赖项时,我就无法再从 Eclipse 中运行 Java 程序。

In your command-line argument file cp.txt escape backslashes ( \\ ) by replacing them with double backslashes ( \\\\ ) or use forward slashes ( / ) instead of backslashes ( \\ ).在您的命令行参数文件cp.txt逃生反斜线( \\ )用双反斜杠(更换它们\\\\ )或使用正斜杠( / )而不是反斜线( \\ )。

See The java Command - java Command-Line Argument Files :请参阅java 命令 - java 命令行参数文件

  • Because backslash ( \\ ) is an escape character, a backslash character must be escaped with another backslash character.因为反斜杠 ( \\ ) 是一个转义字符,一个反斜杠字符必须用另一个反斜杠字符转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM