Java Runtime.exec() program won't output to file - java

I have a program that takes in a file as an input and produces an xml file as an output. When I call this from the command line it works perfectly. I try calling it from a Java program with the following code.
try
{
Process proc = Runtime.getRuntime().exec(c);
try
{
proc.waitFor();
}
catch(InterruptedException e)
{
System.out.println("Command failed");
}
}
catch(IOException e)
{
System.out.println("Command failed");
e.printStackTrace();
}
The program seems to be running fine, as it creates an xml file; however, the xml file is empty when I open it. I'm not encountering any exceptions in my Java program, so I'm baffled as to what the problem could be. Why would the command line program work fine normally, but then when called from Java not output anything to the file it created. I was thinking maybe it was some sort of permissions thing. I tried running the program as sudo (I'm using Linux) but to no avail. This problem doesn't seem to be anything I could find an answer to online. Hopefully somebody on here might be able to tell what's going on. :)

Get the output and error streams from your process and read them to see what is happening. That should tell you what's wrong with your command.
For example:
try {
final Process proc = Runtime.getRuntime().exec("dir");
try {
proc.waitFor();
} catch (final InterruptedException e) {
e.printStackTrace();
}
final BufferedReader outputReader = new BufferedReader(new InputStreamReader(proc
.getInputStream()));
final BufferedReader errorReader = new BufferedReader(new InputStreamReader(proc
.getErrorStream()));
String line;
while ((line = outputReader.readLine()) != null) {
System.out.println(line);
}
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
} catch (final IOException e) {
e.printStackTrace();
}
If there is no output in either stream, then I would next examine the external program and the command being sent to execute it.

Did you try launching the process from outside java?

For me, I wrote a jar file that output a file and ran that from the command line in another java program. It turns out that there was a fundamental check in my jar file that I had forgotten about on the number of characters in an input string (my bad). If the count of the characters was smaller than 8 there was no output file. If the number of characters was greater than 8, the output file came out without any trouble using the following code:
String cmdStr = "java -jar somejar.jar /home/username/outputdir 000000001";
try
{
Runtime.getRuntime().exec(cmdStr);
Runtime.getRuntime().runFinalization();
Runtime.getRuntime().freeMemory();
log.info("Done");
}
catch (IOException e)
{
log.error(System.err);
}
Not sure if I really need everything here but, hey, it works. Note: no waitFor seems to be necessary in my case.

process input (actually output of the process!) and error streams has to be handled before waiting for the process termination.
This should work better
try
{
Process proc = Runtime.getRuntime().exec("anycomand");
BufferedReader outSt = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader errSt = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line;
while ((line = outSt.readLine()) != null)
{
System.out.println(line);
}
while ((line = errSt.readLine()) != null)
{
System.err.println(line);
}
proc.waitFor();
}
catch (final IOException e)
{
e.printStackTrace();
}
but to understand better how Runtime exec works it is worth reading
the classic article
When Runtime.exec() won't
which provide useful sample code (better than the one above!)

Related

Bat file working from terminal not working from Java

I found my command line tool gets stuck in between and needs a enter to process and I found that it’s because of "QUICKEDIT" mode in cmd and we want to disable it to avoid that. So I searched for Java options to disable quick edit mode on my app launch but I got only bat file from here quickedit.bat.
And this bat file works perfect when I run from my command prompt it disable quick edit mode in the current session itself which is the same I want. So I kept that bat file in my folder via installer and run it first on every launch but it’s not turning off the quick edit mode for current session.
I have tried using both process builder and runtime.exec.
Below is my code
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "quickedit.bat");
File dir = new File(System.getProperty("user.home")+File.separator+"AppData"+File.separator+"Local"+File.separator);
pb.directory(dir);
Process p=null;
try {
p = pb.start();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println(line); // ----Here i get the same output i get when i run the bat file
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader inerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((line = inerr.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It gives me this:
When I run my bat file directly like this:
But through Java it didn't disable quick edit in my current command prompt whereas it disables at once I run the actual bat file. So can anyone say the reason or how to fix it or any other way to disable it for ever from Java?
Try pb.inheritIO(); before you call its start method. What you seem to have is a hybrid batch/Powershell script that that relies on stderr to determine which of the two it executes so this should require correct processing of stderr.
I didn't look at your bat file the most common issue on this kind of think is that process run from java did'nt share the environnement variable of your local setup nor jvm a quick fix to verify that is :
pb.environment().putAll(System.getenv());
hoping this will work :) then you just have to found which specific environnment variable is missing :)

is there a way to simplify this terminal class I wrote or make it more efficient :) thnks

To run the terminal from my intelliJ I wrote next code:
public static String runTerminalCommand (String command){
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
try {
while((line = reader.readLine()) != null) {
out.print(line + "\n");
return line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
If there is a way to simplify this :)
I would first look into correctness here; that one line:
return line;
looks suspicious. Or, more precisely: are you sure that your command will always print exactly one line? Because you are returning after reading the first line; and thus omitting any other output.
Besides: you should change your code to use try-with resources instead - your return statement just leaves your readers unclosed. Probably not a problem here because all of that should go away when the process object goes away, but still: bad practice. "Cleanup things" before exiting your methods!
To answer the actual question: after looking into these conceptual things I am pointing out, there isn't much else you could do. Probably use a ProcessBuilder instead of the somehow "outdated" Runtime.exec() call.

Is it possible to use Java SE to enter text on a line?

I'd like to know if there's a way where the Java SE allows a passage to be printed out and then in between the line we can allow the user to type the answer on the line.
To be more clear :
Here's an example:
____ reading, Alice also enjoys listening to classical music.
So, when the text is being drawn out using the buffer reader, the user is able to enter the answer on the line itself.
Here's the method of buffer reader:
public void getCloze(){
File file = new File("cloze.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// show file contents here
System.out.println(contents.toString());
}}
Hope someone can advise me how to and best if there's any tutorial to show the steps.
I dont think it is possible to prompt the user to type in between the already printed line in Java. you have to stop your priniting to take user input and then print further string to the user
It is not entirely clear what your problem is, but you seem to want to know how to write a question or prompt and allow the user to enter the answer on the same line. If so, the "trick" is to use System.out.print(prompt) rather than System.out.println(prompt); i.e. DON'T output a line break after the prompt.
UPDATE - I see what you are asking now.
Well the bad news is that there is no simple way to do that. However, it is doable using something like the charva library or a "curses for Java" library - What's a good Java, curses-like, library for terminal applications?

Runtime.exec - fine for 'echo' 'but not for cat...

I'm having a problem calling some simple command line functions with r.exec - for some reason, given a file X the command
'echo full/path/to/X' works fine (both in the display and with 'p.exitValue()==0', but 'cat full/path/to/X' does not (and has 'p.exitValue()==1') - both 'cat' and 'echo' live in /bin/ on my OSX - am I missing something? Code is below (as it happens, any suggestions to improve the code generally are welcome...)
private String takeCommand(Runtime r, String command) throws IOException {
String returnValue;
System.out.println("We are given the command" + command);
Process p = r.exec(command.split(" "));
InputStream in = p.getInputStream();
BufferedInputStream buf = new BufferedInputStream(in);
InputStreamReader inread = new InputStreamReader(buf);
BufferedReader bufferedreader = new BufferedReader(inread);
// Read the ls output
String line;
returnValue = "";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
returnValue = returnValue + line;
}
try {// Check for failure
if (p.waitFor() != 0) {
System.out.println("XXXXexit value = " + p.exitValue());
}
} catch (InterruptedException e) {
System.err.println(e);
} finally {
// Close the InputStream
bufferedreader.close();
inread.close();
buf.close();
in.close();
}
try {// should slow this down a little
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
You should be consuming stdout and stderr asynchronously.
Otherwise it's possible for the output of the command to block the input buffers and then everything grinds to a halt (that's possibly what's happening with your cat command since it'll dump much more info than echo).
I would also not expect to have to call waitFor() twice.
Check out this SO answer for more info on output consumption, and this JavaWorld article for more Runtime.exec() pitfalls.

running linux copy and rename command with java

File wd = new File("/bin");
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
//out.println("su - root");
out.println("cp /usr/rock/Masterfile.xls /usr/rock/generatedfile/");
out.println("mv /usr/rock/generatedfile/Masterfile.xls /usr/rock/generatedfile/userid.xls");
try {
String line;
while ((line = in.readLine()) != null) {
logger.info(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (Exception e) {
logger.info(e);
e.printStackTrace();
}
}
I am trying to copy master file and want to rename according to the userid. Code does not showing any error but i dont see any file in the folder i specify. I tried with sudo root command even its not copying and renaming the file. How should i do in order to run copy and rename command to run successfully from java program.
You're not reading from the process's standard error. So if your cp and mv commands are reporting errors, you won't be seeing them.
It's possible to read from the process's standard error, but that's complicated if you're using Runtime.getRuntime().exec() because reading from standard error needs to be done in a separate thread to reading from standard output.
Java 5 introduced a new class for running external processes: ProcessBuilder. In my opinion, the single biggest advantage of a ProcessBuilder is that you can redirect the standard error of the process into its standard output. That leaves you with only one stream to read from, and hence no need for a separate thread.
I would recommend replacing your use of Runtime.getRuntime().exec(...) with the following:
ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.directory(wd);
builder.redirectErrorStream(true);
proc = builder.start();
If the files aren't being copied, then chances are that cp and mv are reporting errors. Making this change should hopefully allow you to see the errors being reported.

Categories

Resources