简体   繁体   中英

Java: System.out.println() should write to the console, but it doesn't

I am trying to write Java console application, the code is quite simple:

public class ConsoleTest {
    public static void main(String[] args) {
        System.out.println("test");
    }
}

If I run this application from Eclipse, then i see " test " in Eclipse's "Console", but if I export my app as a " Runnable JAR file " and run it from Windows XP cmd.exe , then nothing is echoed to the console.

On the safe side, i tried to check System.console() , it returns null .

What can be wrong?

How are you running your program outside eclipse?

You should use command line like

java -jar yourjar.jar

or

java -cp yourjar.jar ConsoleTest

If you are occasionally using javaw instead no console output will be produced. The STDOUT of javaw is null . Probably this is what happens when you are clicking on your jar file.

You need to run your jar file from the command line.

If you double click on it, you wont be able to see the command line operations being run in the background. Jar files are usually run by double clicking only when they involve GUI.

To run a jar file from a command prompt, just do this:

java -jar ConsoleTest.jar

Assuming you've set environment variables for java.exe and the current directory has the jar file.

If this doesn't work, then it is likely not your code's fault. There is also the chance that the manifest file pointing to the Main class was set up incorrectly.

Try compiling it into a class from the command line and then running it. Does that work?

javac ConsoleTest.java
java ConsoleTest

有可能你的runnable jar文件没有按预期工作,并且实际上并没有运行你的ConsoleTest类。

Like what Hovercraft Full Of Eels wrote, compile the .java file using cmd.exe with the following command:

javac ConsoleTest.java

Then this will create a .class file, and we want to compile it with this command:

java ConsoleTest

It should then display the "test" output.

you have to install the java jdk and add the root of the directory containing the file java.exe to your system's directories, you will find further informations in the jdk's installation guide.

and then run the file in the console with the command

> java file.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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