This code works fine on Computer A and doesn't work on Computer B ... I can't understand Why..
Nothing Exceptions or anything else ....On Computer A log file was created , on computer B log file was't created.
Computer A and B have the same Java version...
Do you have any ideas?
String str = "cmd /C dir tools>1.log";
try {
Runtime.getRuntime().exec(str);
} catch (Exception e) {
e.printStackTrace();
}
PS
this code works fine on both computers
String str = "cmd /C dir tools";
You have to open the process' output stream to save the output to a file correctly.
You can do this by creating a Process object and saving that to a file:
Process p = Runtime.getRuntime().exec(str);
InputStreamReader reader = p.getInputStream();
BufferedReader buffer = new BufferedReader(reader);
String line = null;
while ((line = buffer.readLine() != null) {
//write stuff to file here
}
Going on what SLaks said -- it is your best bet to use the built-in file APIs.
Here is a link for a general tutorial
Using these APIs will take out any strange environment issues from Computer A to B...to C and so on.
Related
I am trying to print the output of a shell script on the console using java. When I manually run the script, I get
C:/Users/user1/Desktop/shell.sh: line 78: /usr/ucb/ps: No such file or directory
<STATUS>: Probe [ devicename ] is not running!
But, when I try to run it on my Java program, the output is not being printed on the console.
My code is:
ProcessBuilder processBuilder = new ProcessBuilder("C:/Program Files/Git/git-bash.exe","C:/Users/user1/Desktop/shell.sh");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
System.out.println(line);
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
The only output I am getting is "Success". When I debugged my code, I found that the code never enters the condition
while ((line = reader.readLine()) != null)
even though, in the bash terminal, there are lines of output. Why is this happening?
I am stuck at this point and I couldn't find any other explanations for this problem. Kindly help.
You are running git-bash.exe which opens as a windows application. Although Java has access to the stdout/stderr streams of git-bash.exe, these are not necessarily the same as the stdout/err of the internal launch of your shell script within git-bash.exe.
One way to see the stdout/err of your command would be to make a java friendly version of the .sh script which launches your original sh and redirects output to a specific files which you can then access within java afterwards.
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Git/GIT-BASH.EXE","/c/Users/blah/somescript.sh");
somescript.sh:
#!/bin/sh
runtheoriginalcommand > ~/somepath.out 2> ~/somepath.err
You could also add extra args to wrapper to pass the out/err files to be used so there is no contention with any other launches or hardcoded output files.
I´ve run into problem. I want to convert video using ffmpeg but it gives me no output
public void convert(String inputFile, String outputFile, String ... optionalParams) {
ProcessBuilder processBuilder = new ProcessBuilder("ffmpeg", "-i", "\"" + inputFile.trim() +"\"", "\""+ outputFile.trim() + "\"");
DownloadRecord downloadRecord = table.getItems().get(0);
downloadRecord.setStatus("Downloading");
// Try to execute process
try {
// Set the working directory
processBuilder.directory(new File(workingDirectory));
//Start the process
Process process = processBuilder.start();
// Read the output from cmd
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader ra = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
String errline;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
while ((errline = ra.readLine()) != null) {
System.out.println(errline);
}
process.waitFor();
System.out.println("the end");
} catch(IOException | InterruptedException e) {
System.out.println(e.toString());
}
}
I've been searching on stackoverflow and find some solutions, none worked. What I tried and figured out so far
No output or error output
I tried to remove backslashes from ProcessBuilder, it
also gives me no output
I tried to let the program running, but it never finishes
I tried to use full path to the ffmpeg, no changes
I tried to run the video, no error
I am using
Netbeans IDE so I tried clean and rebuild project, no change
process also never finishes
I would like from it an output. Does someone know what I am doing wrong here ?
I fixed it by reinstalling the ffmpeg. Just went ffmpeg website downloaded newest version, replaced files in folder and it works
Edit:
It just works for files with less thatn 2 mins for some reason, more thatn 2 mins files are behaving like this
I start converting, it will not convert entirely until program runs. After I exit the program it will finish. It´s strange behaviour.
I have a java program that opens up a .exe file. What i want to do is,
1)Run the .exe file when the java program is executed - Runs perfectly
2) When running the same code again, I want to reopen the previously executed exe.I dont want the .exe file to execute again.
EDIT:
Is there a way to do the above? My only concern is the 2nd question. I have made the 1st question to work
On the request of Luffy. This is the code that i had used to get the list of running process and check whether a particular exe is running or not. Hope it helps for others.
try
{
String line;
String pidInfo = "";
Process proc = Runtime.getRuntime().exec("wmic.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
oStream .write("process where name='test.exe'");
oStream .flush();
oStream .close();
while ((line = input.readLine()) != null) {
pidInfo+=line;
}
input.close();
if(pidInfo.contains("test.exe"))
{
System.out.println("exe already running");
}
else
{
System.out.println("exe not running");
Process p = Runtime.getRuntime().exec(new String[] {"C:\\Program Files (x86)\\ToTestEXE\\test.exe"});
}
}
catch (IOException e)
{
e.printStackTrace();
}
I have a computer algebra program (called Reduce) that works in the shell in an interactive manner: launch Reduce in the shell, then you can define variables, compute this and that, and what not. Reduce prints the output into the shell. My idea is that I want to build a frontend for this text-based program that evaluates its output and converts it into a nice LaTeX style formula. For this I want to use Java.
I can start Reduce via exec(). But how can I emulate text input to the opened shell, and how can I read back what Reduce writes into the shell?
Thanks
Jens
Edit 1: Current Code
// get the shell
Runtime rt = Runtime.getRuntime();
// execute reduce
String[] commands = {"D:/Programme/Reduce/reduce.com", "", ""};
Process proc = null;
try {
proc = rt.exec(commands);
} catch (Exception e) {
System.out.println("Error!\n");
}
// get the associated input / output / error streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
try {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
try {
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
}
You need to get the streams associated with the process including the InputStream, OutputStream, and ErrorStream. You then can send messages to the process via the OutputStream and then read info from the process via the InputStream and the ErrorStream.
From some code of mine:
final ProcessBuilder pBuilder = new ProcessBuilder(TEST_PROCESS_ARRAY);
final Process proc = pBuilder.start();
procInputStream = proc.getInputStream();
errorStream = proc.getErrorStream();
errorSBuffer = new StringBuffer();
streamGobblerSb = new StreamGobblerSb(errorStream, "Autoit Error", errorSBuffer);
new Thread(streamGobblerSb).start();
final Scanner scan = new Scanner(procInputStream);
You may want to look into using the Process class.
http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
I believe you may be able to start the process, and then use getOutputStream() to feed commands into the process.
While this is not strictly an answer, I discovered that it is more convenient for me to stick with PHP's function proc_open(). That way I can include the output directly in the frontend and do not need to worry about the communication between my Java program and the html frontend.
For everybody who wants to stick to the Java method: the article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html is a good reference.
Here's the code: it successfully opens a terminal but nothing is displayed on the output
try {
String command= "/usr/bin/xterm";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
BufferedWriter os =
new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));
BufferedReader is =
new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = is.readLine()) != null) {
System.out.print(line);
}
} catch (Exception io) {
}
Don't write empty catch-blocks. It's just wrong and it will cost you many hours of debugging after which you'll feel ... less than perfect.
xterm produces no output by default. It just displays a window. Try starting xterm in a terminal and see which output it produces (in the original terminal, not in the new window!).
Read When Runtime.exec() won't and follow all of its advice.
Have you read When Runtime.exec() won't. If you read the whole article you will avoid and understand many pitfalls of the exec command.
Then you can read up on ProcessBuilder which is a more modern way to invoke other processes.
Ps. Empty catch block swallow exceptions and make it harder to debug.