I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!
Runtime.getRuntime().exec("cmd.exe /c demo.bat");
Runtime.getRuntime().exec("demo.bat");
i tried to do work with process and i wrote the code below. it retuened
java.lang.IllegalThreadStateException:process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at Test.Asli.main(Asli.java:38)
this is the code:
try{
Runtime rt = Runtime.getRuntime();
Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe");
int b = proc.exitValue();
// int exitVal = proc.exitValue();
//System.out.println("Process exitValue: " + exitVal);}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Try the following:
String[] cmd = {"cmd.exe", "/c", "demo.bat");
Runtime.getRuntime().exec(cmd);
I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.
Try this:
Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
Use this:
try {
Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
} catch(Exception e) {
e.printStackTrace();
}
It even hides the annoying prompt window (if you want that)
Related
im calling multiple batch files in Java with the ProcessBuilder like
ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "Start", "batchTest.bat");
File dir = new File(path);
processBuilder.directory(dir);
try {
Process p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now i want the information that the script is done in java. Like just a sysout when the script is completly finished. process.isAlive() turns false before the script is done. And also process.witFor() doesnt get the job done. Maybe someone has an idea or a workaround?
Okay, i got it. process.waitFor() only works if you add the parameter "/wait" to the Constructor of the ProcessBuilder.
new ProcessBuilder("cmd", "/c", "Start", "/wait", "batchTest.bat");
I already create the .sh file, and the inside is:
sudo iptables --flush
sudo iptables -A INPUT -m mac --mac-source 00:00:00:00:00:00 -j DROP
It works normally when I run it on the terminal, but when I use processbuilder, it didn't do anything. No error, but didn't happen anything, this is the code on my java:
Process pb = new ProcessBuilder("/bin/bash","/my/file.sh").start();
I already looking for the answer, but I still failed to run the .sh file, even I do the same thing with people that already done it.
Sorry if this is a bad question, thank you.
Are you sure that the bash is not run? Do you checked the Process object returned by the startmethod? You can get the output value, the output stream, etc. from this objects.
Check your streams and exitvalue for errors... sudo is probably the problem here.
Not necessarily the best code but it gets the job done. Executes a process, takes the process.streams and prints them to System.out. Might helpt to find out what the issue actually is atlest.
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
final Process proc = pb.start();
final StringBuilder builder = new StringBuilder("Process output");
final Thread logThread = new Thread() {
#Override
public void run() {
InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
do {
line = reader.readLine();
builder.append("");
builder.append(line == null ? "" : line);
builder.append("<br/>");
} while(line != null);
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
}
}
}
};
logThread.start();
int retVal = proc.waitFor();
System.out.println(builder.toString());
From Java API Runtime : http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
// Java runtime
Runtime runtime = Runtime.getRuntime();
// Command
String[] command = {"/bin/bash", "/my/file.sh"};
// Process
Process process = runtime.exec(command);
Also you should be careful with sudo commands that may ask for root password.
I am trying to run a simple "cecopy" in java. I call "cmd.exe" and pass the command through. It creates the directories but doesnt carry out the copy.
Below is the command I am using, set as a string in java:
String cmd = "mkdir \"C:\\\\Dominos\\\\DATFiles\" >> log.txt\n"
+ "\n" +
"cecopy \"dev:\\Application\\\\MCL\\\\Projects\\\\Default\\\\aa.dat\" \"C:\\\\Dominos\\\\DATFiles\");
Below is how I am calling command prompt to execute the DOS statement:
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec("cmd.exe /c" + cmd); // Call CMD
p.waitFor(); // Wait till CMD finishes
} catch (InterruptedException | IOException ex) {
Logger.getLogger(readData.class.getName()).log(Level.SEVERE, null, ex);
}
Any help?
Thanks in advance!
You can use process builder. It handles commands with arguments neatly.
ProcessBuilder processBuilder = new ProcessBuilder();
p.command("cmd_to_run", "args_if_any");
p.start();
I am creating a code editor for Java source files by using Java. When I click on the RUN menu, it perfectly opens cmd and run javac command, but the problem is that it immediately gets closed and I want something like pause.
This is my code:
Runtime rt = Runtime.getRuntime();
try {
rt.exec("cmd.exe /c start java Maq");
} catch (IOException e1) {
e1.printStackTrace();
}
How to get rid of this problem?
Now that you have confirmed that you actually need javac and are working on an IDE/editor, the right way to handle compiling errors is by compiling from the JRE using javax.tools.JavaCompiler.
The JavaCompiler gives you refined control, cross platform functionality and is always there. You can take a look at the JavaDoc to get yourself started. Here's a nice example of its usage.
I have used it personally for an IDE like project and it did exactly what you would expect from an in-program compiler.
The 'start' bit of your command detaches Java from the cmd process.
You're probably best off writing a batch script containing something like this:
#echo off
java Maq
pause
Then just call that batch file using Runtime.exec(...)
Answer from this question helped me :)
Runtime rt = Runtime.getRuntime();
try {
rt.exec("cmd.exe /c cd /d d: & start cmd.exe /k javac Maq.java");
} catch (IOException e1) {
e1.printStackTrace();
}
To see javac's output, you can't use Runtime.exec(). Use a ProcessBuilder instead. Your code can look something like this:
ProcessBuilder pb = new ProcessBuilder("javac", "Maq.java");
pb.directory(new File("/path/to/source/code/"));
Process p = pb.start();
InputStream in = p.getInputStream(); // this is connected to the System.out from javac
int exit = p.waitFor(); // wait for javac to finish
StringBuilder text = new StringBuilder();
char[] buf = new char[1024]; int read;
while ((read = in.read(buf)) != -1)
text.append(new String(buf, 0, read));
text.append("\n\njavac returned with exit code ").append(exit);
// display text - it now contains javac's output and its exit code
JFrame f = new JFrame("javac's output");
JTextPane tp = new JTextPane();
tp.setText(text.toString());
tp.setEditable(false);
f.setContentPane(tp);
f.setSize(500, 400); // or whatever
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
I have a game, and I am going to enable auto-restarting features. It will happen every 24 hours, which is easy to make. However, the problem is, I don't know how to open run "run.sh" (which executes the Java Game Server).
The code is going to shut down everything first, and right before System.exit is called, it should open the run.sh in a new terminal. How would I do this?
This is the method I am currently using, but it's giving me this error.
public static boolean start() {
try {
List<String> command = new ArrayList<String>();
command.add("cd /root/Dropbox/[SALLESY] 742 Server");
command.add("java -Xmx1024m -Xss2m -Dsun.java2d.noddraw=true -XX:+DisableExplicitGC -XX:+AggressiveOpts -XX:+UseAdaptiveGCBoundary -XX:MaxGCPauseMillis=500 -XX:SurvivorRatio=16 -XX:+UseParallelGC -classpath bin:data/libs/* com.sallesy.Application");
ProcessBuilder builder = new ProcessBuilder(command);
Process proc = builder.start();
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
Error:
sh script.sh
Cannot run program "cd /root/Dropbox/[SALLESY] 742 Server": error=2, No such file or directory
Could not start a new session...
Try escaping the string:
"cd /root/Dropbox/\[SALLESY\]\ 742\ Server"
Nice game m8 did u make it urself!!?
also here :^)
"cd /root/Dropbox/\[SALLESY\]\ 742\ Server"