How can I run a Java program from the command line on Windows?
I’m trying to execute the following Java program from the command line in Windows:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFile {
public static void main(String[] args) {
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File("input.txt");
File bfile = new File("inputCopy.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
How can I run this program from the command line in Windows? I’m not sure how to execute it, and I thought the JVM would make it easier to run Java programs anywhere. Why is it different in this environment?
I’ve been through this myself—getting Java to run via CMD on Windows can be tricky at first! But don’t worry, let’s break it down.*
Before you can run Java from command line, you need to check if Java is installed and properly configured:
Open Command Prompt and type:
java -version
If this returns a Java version, you’re good. If not, install Java first.
If Java is installed but still not working, check your environment variables:
Set JAVA_HOME: Find your JDK installation path (e.g., C:\Program Files\Java\jdk-14
) and set it as JAVA_HOME.
Update PATH: Add C:\Program Files\Java\jdk-14\bin
to your PATH variable.
Now, restart CMD and try running Java again!"
@joe-elmoufak nailed the setup part! Now, let’s actually run Java from command line by compiling and executing a Java program.*
Here’s how:
Navigate to your Java file’s directory in CMD:
cd path\to\your\java\file
Compile your Java program:
javac CopyFile.java
This creates a CopyFile.class
file.
Run your Java program:
java CopyFile
If everything’s set up right, you should see "File is copied successfully!"
as output.
Simple, right?
Once you get used to it, running Java from CMD becomes second nature!"
Great breakdown, Toby! But if working in CMD feels tedious, you might want to use an IDE or text editor that supports running Java more seamlessly.
Run Java from command line inside an IDE:
IntelliJ IDEA / Eclipse
Right-click CopyFile.java
→ Select Run 'CopyFile'
No need to manually compile; the IDE handles it.
Visual Studio Code
Install the Java Extension Pack + Code Runner extension.
Open CopyFile.java
→ Press Ctrl + Alt + N to run.
This way, you get the best of both worlds—running Java from the command line but with a much smoother experience!"