Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
Answer from kol on Stack OverflowRuntime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
You can also watch the output like this:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.
EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:
String[] command = new String[] {
"choice",
"/C",
"YN",
"/M",
"\"Press Y if you're cool\""
};
String inputLine = "Y";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write(inputLine);
writer.newLine();
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:
Press Y if you're cool [Y,N]?Y
Source: javaindos.
Let's say your file is in C:\mywork\
Run Command Prompt
CopyC:\> cd \myworkThis makes C:\mywork the current directory.
CopyC:\mywork> dirThis displays the directory contents. You should see filenamehere.java among the files.
CopyC:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\binThis tells the system where to find JDK programs.
CopyC:\mywork> javac filenamehere.javaThis runs javac.exe, the compiler. You should see nothing but the next system prompt...
CopyC:\mywork> dirjavac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.
CopyC:\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!
To complete the answer :
The Java File
Copy
TheJavaFile.javaCompile the Java File to a *.class file
Copy
javac TheJavaFile.java- This will create a
TheJavaFile.classfile
- This will create a
Execution of the Java File
Copy
java TheJavaFileCreation of an executable
*.jarfileYou've got two options here -
With an external manifest file :
Create the manifest file say - MANIFEST.mf
The MANIFEST file is nothing but an explicit entry of the Main Class
jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class
Executable by Entry Point:
jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
To run the Jar File
Copy
java -jar TheJavaFile.jar
cmd - How do I run a java program through the console (command prompt)? - Stack Overflow
Running Java in Command Prompt?
How do I execute Command Prompt commands in Java 21.0.2
How do I execute Windows commands in Java? - Stack Overflow
Videos
Put all you files in the directory javaprogram
I mean all of them : Snake.java,Board.java,head.png,dot.png and apple.png
Then you edit files Snake.java and Board.java
In Snake.java, remove package declaration at top of the file.
In Board.java, remove package declaration at top of file as well as edit the path of image files.
eg. ImageIcon iid = new ImageIcon("dot.png");
Once you have done all the above mentioned changes, use the below mentioned command:
javac *.java - to compile files
javaw Snake - to execute the program
Check whats the difference between java and javaw and javac.
If you are sending this game to someone just pack it in executable jar file.
Give my answer green tick :P
After running
javac filename.java
You can run the following commande:
java filname
Note that in the above commande filename doesn't take extension
If you encounter some errors, you try to remove
package com.zetcode;
at the beginning of each file and compile again and then execute
Second Edit: May have fixed the Environment Variables to work with JAVA_HOME. Minor change to what was printed but was able to run the file like so:
C:\Users\Test>cd Documents\MyFirstProgramFolder C:\Users\Test\Documents\MyFirstProgramFolder>java MyFirstProgram We did it! Again! Number 3!
Again, making sure I was in the right directory was the first issue, but now I may have the Environment Variables fixed. I hope at least. Thank you again everyone.
Edit: Have my issue mostly solved. I am able to compile and run the code. cd-ing to the correct directory seemed to be the issue in the command prompt and that is all I really need for now. Thank you to everyone who took the time try to help me!
Hello! I am new to learning Java but have been stuck on a single issue for the past day and a half. I have recently started reading Head First Java to try and teach myself Java. I took a single programming class that was taught in Java 3-4 years ago. All of the programming experience I have has always been in some sort of IDE. In Head First Java they want you to work through the command line after writing code. I have been entirely unsuccessful at setting up Java to work through the command prompt. I have now tried to download 2-3 different JDK's, followed 2-3 tutorials on how to just get "Hello World" to print, and followed a guide on how to set up the Java Environment. None have been successful and I am frequently met with the below errors/issues when I try to parse together my understanding trying to fix the issue. I would really like to learn how to actually do things without the need of an IDE. Any help at all would be greatly appreciated! So the question summed up, is more or less where am I going wrong for setting up the Java environment, or JVM?
In the Command Prompt:
C:\Users\Test>"C:\Program Files\Java\jdk1.8.0_161\bin"\Javac MyFirstProgram.java
javac: file not found: MyFirstProgram.java
Usage: javac <options> <source files>
use -help for a list of possible options
In Windows Powershell:
PS C:\Users\Test\Documents\MyFirstProgramFolder> "C:\Program Files\Java\jdk1.8.0_161\bin"\javac MyFirstProgram.java
At line:1 char:41
+ "C:\Program Files\Java\jdk1.8.0_161\bin"\javac MyFirstProgram.java
+ ~~~~~~
Unexpected token '\javac' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Below are some of the websites I have tried:
https://www.instructables.com/How-to-Make-Your-First-Computer-Program/ - This instructables link is what I just used to receive the above responses.
https://www.tutorialspoint.com/java/java_environment_setup.htm
https://www.geeksforgeeks.org/setting-environment-java/
The Code:
class MyFirstProgram {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}I tried using the following function:
Runtime.getRuntime().exec("DIR")but it doesn't get executed and my IDE always shows the following warning:
The method exec(String) from the type Runtime is deprecated since version 18Java(67110270)
I hope this helps :)
You could use:
Runtime.getRuntime().exec("ENTER COMMAND HERE");
an example. 1. create cmd 2. write to cmd -> call a command.
try {
// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();
} catch (IOException e) {
}
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
Copyimport java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can try this:-
CopyProcess p = Runtime.getRuntime().exec(command);