I am trying to call a bat file from my Java function. Looks like some issue in the way I am calling the bat file. The batch file is not called from the method. Any help would be appreciated.
private static void Run_Main() throws InterruptedException, SQLException, IOException {
int set_value=0;
while ((set_value=Find_Flag()) !=0){
System.out.println("Set_Value"+set_value);
System.out.println("Staging load is not completed ..Revisiting after 15 minutes....");
Thread.sleep(900000);
set_value=Find_Flag();
}
System.out.println("Staging load is Completed and launching Proudction Load now");
//Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "C:/exec/DW_Init_Load.bat" } );
String filePath = "C:/exec/DW_Init_Load.bat";
try {
Process p = Runtime.getRuntime().exec(filePath);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Production Load is finished");
}
I am interested to know what is the mistake I have made in the code
Adding p.waitFor() helped me solve this issues. Initially the block is not waiting for the process to complete.
Related
Is it possible in Java to seperate a subprocess so that it isn't longer a subprocess in the end?
Or to run a external process, that isn't a subprocess.
I want to start some big external process in linux. But with ProcessBuilder or Runtime.exec, it's my subprocesses and when I try to start big processes for example four minecraft server, I get a pthread_create exception in the end.
Is this possible in Java?
I just tested a small sample
import java.io.IOException;
public class Forking {
public static void main(String[] args) {
Process exec = null;
try {
exec = Runtime.getRuntime().exec("sleep 360");
} catch (IOException e) {
e.printStackTrace();
}
if (exec != null) {
System.out.println(exec.isAlive());
}
}
}
It runs with no exceptions and after it exits if you ps aux|grep sleep you will see that the sleep 360 is there running.
I'm trying to run an Ubuntu image from a java program using a script; here is how:
my java code:
public static void main(String[] args) {
executeCommand("/home/abrahem/IdeaProjects/untitled3/src/createContainer.sh");
}
public static void executeCommand(String filePath) {
File file = new File(filePath);
if (!file.isFile()) {
throw new IllegalArgumentException("The file " + filePath + " does not exist");
}
try {
if (isLinux()) {
Process p = Runtime.getRuntime().exec("sh " + filePath);
p.waitFor(); // i tried to remove this but still not work for my me
} else if (isWindows()) {
Runtime.getRuntime().exec("cmd /c start " + filePath);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
here is my createContainer.sh script file:
#!bin/sh
sudo docker run ubuntu
when I go to bin and type:
docker ps
or
docker ps -a
It should show the running Ubuntu container, but it doesn't.
Note: there is nothing wrong with the shell location; I try to create file in shell file and it works.
You do not capture any error messages or normal output from your process. Maybe it just works?
Use getErrorStream() and getOutputStream() methods of Process to capture the output from the process somewhat like described here. You may just see the expected output. If not, it should be the error message on the error stream.
I am attempting to have my java program execute a python script using
import java.lang.Runtime;
public class test
{
public static void main(String[] args)
{
try
{
System.out.println("testing");
Runtime.getRuntime().exec("/usr/bin/python print.py");
}catch(Exception e){System.out.println("not working");}
}
}
However, nothing is shown on the terminal, (print.py simple prints "THIS IS WORKING"). In contrast to this, when I use
Runtime.getRuntime().exec("touch dog.txt");
A file named dog.txt is created.
I also attempted to run
Runtime.getRuntime()exec("./shellscript.sh");
Which is just a script that runs the touch command, that also did not work.
Not really sure what the issue is here, and even more interesting is that yesterday the java program was working as intended with no large changes to my computer in the time in between. Anybody have any ideas on whats going on?
I am not receiving any errors.
I guess you have to wait to end of script execution.
try {
Process process = Runtime.getRuntime().exec("/usr/bin/python print.py");
process.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can try to read exitCode from process ;-)
Ok I ended up having success by using
process p = Runtime.getRuntime().exec("./pyshellthing.sh");
p.waitFor();
The shell script simply executes the python script.
I wrote a process manager program one of the things that it does is to exit all running processes when it shut down
,so there is the code
public void stop_all() throws IOException {
Process p = Runtime.getRuntime().exec("kill -9 -1");
System.out.println("killed");
}
and there is the action on the button
private void exitButton(java.awt.event.ActionEvent evt) {
Run ob = new Run();
try {
ob.stop_all();
} catch (IOException ex) {
Logger.getLogger(mainmenu.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
}
i have no idea why it doesn't work ,
i execute that command in the terminal and it works fine
please help :)
I am still skeptical about the permissions of the program. But, from this reference you need to specify the command path in your exec().
So your code should probably be:
public void stop_all() throws IOException {
Process p = Runtime.getRuntime().exec("/bin/kill -9 -1");
System.out.println("killed");
}
So I have a method to write a string to a file:
public static void saveStringToFile(String path, String string) {
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter out = null;
try {
out = new FileWriter(path);
out.write(string);
if (out != null) {
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And my test class with the following setUp method which runs before each test (to delete the testfile before each one):
public static final String TEST_FILE = "somefile.xml";
//...
#Before
public void setUp() throws IOException {
if (MyCustomClass.fileExists(TEST_FILE)) {
new File(TEST_FILE).delete();
}
}
Each of my test tries to write something to the file using the method saveStringToFile(). It succeeds like for a couple of times, but a some random point I finally get the java.io.IOException: Access is denied. Got no idea why this happens - sometimes it occurs in test1, sometimes in test3...
It was working OK, when I was using Java7 FileIO, but I needed to migrate back to Java6...
Are you testing that you are able to create, write to and delete a file, or are you testing what is written to the file?
If the latter, then perhaps you should be mocking/overriding the saveStringToFile( ... ) method and instead focus on verifying that the code you're unit testing actually produces the correct output.
If the former, then I quite agree with #Omaha's suggestion that your test runner is likely running several tests in parallel.
Hope that helps.
There's some problems with the exception handling. The call to out.close() should be within a separate try-catch block inside a finally block. If an exception is thrown when writing to the file, the file is never closed.
I would recommend looking at something like Apache Commons IO which has many useful IO methods like FileUtils.writeStringToFile().
So, probably JUnit wasn't running it parrallel, cause as I suppose It doesn't do it by default.
The problem was in my readfile method:
private String readFile(String path) throws FileNotFoundException {
return (new Scanner(new File(path))).useDelimiter("\\Z").next();
}
To work fine I had to fix
private String readFile(String path) throws FileNotFoundException {
Scanner scanner = (new Scanner(new File(path)));
String s = scanner.useDelimiter("\\Z").next();
scanner.close();
return s;
}
The close() method for Scanner was the key...