I’m trying to execute a Java program from the command line in Windows. Here is my code:
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 successful!"); } catch (IOException e) { e.printStackTrace(); } } }
I’m not sure how to execute the program – any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?
Advertisement
Answer
Source: javaindos.
Let’s say your file is in C:mywork
Run Command Prompt
C:> cd myworkThis makes C:mywork the current directory.
C:mywork> dirThis displays the directory contents. You should see filenamehere.java among the files.
C:mywork> set path=%path%;C:Program FilesJavajdk1.5.0_09binThis tells the system where to find JDK programs.
C:mywork> javac filenamehere.javaThis runs javac.exe, the compiler. You should see nothing but the next system prompt…
C:mywork> dirjavac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.
C:mywork> java filenamehereThis runs the Java interpreter. You should then see your program output.
If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!