Running command prompt command in English - java

I want to run a command line programme on Windows, here is the code.
public static String runcmd(String cmd) throws IOException {
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while (true) {
line = r.readLine();
if (line == null)
break;
sb.append(line + "%SKIPLINE%");
}
System.out.println(sb.toString());
return sb.toString();
}
Everything work fine, except that it prints out the output in Chinese because my Windows language is set to Chinese. Is there any ways to make it output in English?

Check this link: how to detect operating system language (locale) from java code
What you want to find is a way to temporarily set your locale in the program to English.

Try this:
https://wandersick.blogspot.com/p/change-non-english-command-line.html
Or
Execute
chcp 437
in the cmd prompt.
For example:
C:\Users\javaserv> chcp 437
Active code page: 437
Hope it helps!

Related

Issues with BufferedReader reading output from CMD processbuilder (JAVA)?

I am running into some problems using ProcessBuilder, Process, and BufferedReaders in my Java program. For some inputs, the function runs perfectly but with others the BufferedReader reads nothing and returns empty strings. I am not sure what may be causing this bug.
I have tried debugging and for those situations where nothing is being read, the BufferedReader is completely skipping the loop. For example, when I pass in the command as 'ipconfig', which has >50 lines of CMD output, it returns every line exactly as displayed. But when I pass in the command as 'java -version', it completely skips the output (there are 3 lines that should be read).
ProcessBuilder/Reading function:
public static String runCommandToStdOut(String command) throws InterruptedException, IOException {
StringBuilder sBuilder = new StringBuilder();
pBuilder = new ProcessBuilder();
String[] processArray = command.split(" ");
pBuilder.command(processArray);
process = pBuilder.start();
process.waitFor();
BufferedReader bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//reading cmd output to string
String line = "";
while ((line = bReader.readLine()) != null) {
sBuilder.append(line);
sBuilder.append(System.getProperty("line.separator"));
}
return sBuilder.toString();
}
How I am calling the function:
try {
String stdOut = osCommandService.runCommandToStdOut("java -version");
}
The stdOut string in the second code section is empty. That means the line 'sBuilder.toString' is an empty string after the function is run. The output that I see when I run 'java -version' directly in my cmd prompt is 3 lines long, which evidently isn't being read properly.

Java doesn't print out shell echo

I'm running a shell script using:
Runtime.getRuntime().exec(command);
Everything works fine, exept for the output. So, this script
echo "opening gedit..."
gedit
Opens gedit, but when running from Java I don't get any output. What is the problem?
String line;
Process p = Runtime.getRuntime().exec(...);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
As mentioned in Printing Runtime exec() OutputStream to console

Running Bash from java does not work

I have this bash:
#!/bin/bash
# File to be tagged
inputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/Text.txt"
#inputfile="test/SampleInputs/longParagraph.txt"
# Tagged file to be created
#outputfile="test/SampleOutputs/NERTest.conll.tagged.txt"
outputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/1.Generate-Basic-Questions/Tagged-Named-Entites-Text.txt"
# Config file
#configfile="config/conll.config"
configfile="config/ontonotes.config"
# Classpath
cpath="target/classes:target/dependency/*"
CMD="java -classpath ${cpath} -Xmx8g edu.illinois.cs.cogcomp.LbjNer.LbjTagger.NerTagger -annotate ${inputfile} ${outputfile} ${configfile}"
echo "$0: running command '$CMD'..."
$CMD
When I run either java codes below they do not give any errors but they just show the bash file in my Eclipse Console, in other words they do not run the bash !! and the value for process.exitValue() is 1, by the way, my OS is CentOS, linux.
Firs JAVA code :
try {
Process process = new ProcessBuilder(command).start();
process.waitFor();
System.out.println(process.exitValue());
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
Second JAVA code :
String command = "/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/"
+ "SinaGolestanirad-Project/1.Generate-Basic-Questions/1.IllinoisNerExtended-DO-NOT-OPEN-BY-ECLIPSE/plaintextannotate-linux.sh";
StringBuffer output = new StringBuffer();
Process p;
try {
String[] cmd = new String[]{"/bin/bash",command};
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
I also checked the bash file permission and it is executable as a program.
How can I run the bash file? The bash should run another program written in java.
-- LeBarton what is the exit code?
Check the output of p.exitValue()
p.waitFor()
InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());
While (inputStreamReader.ready()) { System.out.println(inputStreamReader.read(); }
This will show you the error output. Add this to the bottom below the try.. catch.
You will see the output that you would see on the command line. It will help you narrow down the error.
I found a link which may help, if your bash read some environmental variables.
$PATH variable isn't inherited through getRuntime().exec

Double linebreak with BufferedReader on Win XP, but not other OSs...same code

I have some code that does a Runtime exec and parses the results. On linux and Windows7, the code works fine for parsing the system commands, but on Win XP I am getting a blank line ("") between each line that has content. Any ideas what might be happening here?
Process output = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));
while ((line = br.readLine()) != null)
{
//do stuff
}
There's a difference between the end of line character(s) for Unix vs Windows:
Unix:
\n (0x0A = LF)
Windows:
\r\n (0x0D = CR + 0x0A = LF)
This has to be handled by your application.

handling c executable file using java

I want to run a C/C++ program's exe file using java.......and handle its input and output......
my code is
import java.io.*;
class run2 {
public static void main(String[] args) throws java.io.IOException {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/C";
// command[2] = "java Run1";
command[2] = "start C:\\WE.EXE";
Process p = Runtime.getRuntime().exec(command);
String i = "20";
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedWriter st = new BufferedWriter(new OutputStreamWriter(
p.getOutputStream()));
String s = null;
System.out.println("Here is the standard output of the command:\n");
s = stdInput.readLine();
System.out.println(s);
st.write(i);
st.newLine();
st.flush();
while ((s = stdInput.readLine()) != null) {
System.out.println("Stdout: " + s);
}
try {
System.out.println("Exit status = " + p.waitFor());
}
catch (InterruptedException e) {
}
stdInput.close();
}
}
i am getting an error which says pipes is closed
do help me out.....
Well, first of all, if there isn't a WE.EXE in C:/, that could be an issue. If no process is ever launched, of course you can't do anything with its input/output pipes.
However, presuming you have a WE.EXE, your error is probably at:
st.flush();
Your application is opening up WE.EXE in command prompt, or cmd.exe, who will take care of both standard input and standard output. Your call stdInput.readLine(); will wait until WE.EXE, and therefore cmd.exe, terminates, at which point the output stream will be closed (and you obviously can't write onto a closed pipe).
So if you want to handle input and output yourself, you should launch WE.exe directly, like:
Process p = Runtime.getRuntime().exec("C://WE.EXE");
Additionally, you may consider using ProcessBuilder instead of Runtime.exec.
Small detail, but consider using Java's naming conventions--for example, your class name would be Run2 (or something more descriptive) instead of run2.
You are trying to read from a stream (stdInput) that does not exist yet.
It won't exist until the WE.EXE program writes something to it.
Just wait until you send the commands to the program.
In other words, take out the first input line, and it will work fine.
//s = stdInput.readLine();
System.out.println(s);
st.write(i);
st.newLine();
st.flush();
while ((s = stdInput.readLine()) != null)
{ System.out.println("Stdout: " + s); }

Categories