I am trying to read a file and then take the contents of that file and have it executed as user input. I am using Scanner for reading files and user input but I am not sure if this is the correct way to go about this since Scanner for input can only System.in and so I am not sure how to pass data from file into input scanner for it to execute in the console. This is my code below for reading class
public class readingFile {
Scanner fileReading = new Scanner(new File("somecontent.txt"));
Scanner input = new Scanner(System.in);
public readingFile() throws FileNotFoundException {
}
public void startReading()
{
System.out.println("reading file...");
while(fileReading.hasNextLine()){
String data = fileReading.nextLine();
System.out.println(data);
Scanner input = new Scanner(System.in);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class readingFile {
static String javaFileFullPath = "D://myfolder/Program.java";
public static void main(String[] args) {
executeJavaFile();
}
public static void executeJavaFile() {
try {
System.out.println("executing java program from file....");
Process compileProcess = Runtime.getRuntime().exec("cmd /c javac "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(compileProcess.exitValue());
BufferedReader inputReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
String line = "";
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
}
inputReader.close();
Process runProcess = Runtime.getRuntime().exec("cmd /c java "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(runProcess.exitValue());
BufferedReader inReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String lineStr = "";
while ((lineStr = inReader.readLine()) != null) {
System.out.println(lineStr);
}
inReader.close();
} catch (Exception ex) {
System.out.println("Exception:"+ex.getMessage());
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class readingFile {
static String javaFileFullPath = "D://myfolder/Program.java";
public static void main(String[] args) {
executeJavaFile();
}
public static void executeJavaFile() {
try {
System.out.println("executing java program from file....");
Process compileProcess = Runtime.getRuntime().exec("cmd /c javac "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(compileProcess.exitValue());
BufferedReader inputReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
String line = "";
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
}
inputReader.close();
Process runProcess = Runtime.getRuntime().exec("cmd /c java "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(runProcess.exitValue());
BufferedReader inReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String lineStr = "";
while ((lineStr = inReader.readLine()) != null) {
System.out.println(lineStr);
}
inReader.close();
} catch (Exception ex) {
System.out.println("Exception:"+ex.getMessage());
}
}
}
Related
I got a code which is running and displaying output successfully if I am executing something like "dir" but not displaying the output if I am running "java -version" or other command from java. Please help:
public static void execJob(){
try{
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.directory(new File("src"));
Process process = pb.start();
IOThreadHandler outputHandler = new IOThreadHandler(process.getInputStream());
outputHandler.start();
process.waitFor();
System.out.println(outputHandler.getOutput());
}catch(Exception e) {
System.out.println(e.toString());
}
}
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
Scanner br = null;
try {
br = new Scanner(new InputStreamReader(inputStream));
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
}
java -version writes to stderr, so you need pb.redirectErrorStream(true); to capture the output.
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.redirectErrorStream(true);
...
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line).append(System.getProperty("line.separator"));
}
}
}
public String getOutput() {
return output.toString();
}
}
import java.io.*;
public class ColorTest {
public static void main(String [] args){
try{
//Process p = Runtime.getRuntime().exec("cmd /c color 0a");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readline()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not understanding why the command won't execute. The line that is commented is the one I need help with.
I relaunch the child process every time than i need to obtain a random number, but i think that it can be done using outPutStream but i don't know how. I saw the others post but i don't found nothing relevant for my problem. I don't want to use sockets.
Main Process.
public class ejercicio7 {
public static void main(String [] args){
boolean cerrado = false;
try {
while(!cerrado){
String entrada = JOptionPane.showInputDialog(null, "Introduce una entrada");
Process proceso = Runtime.getRuntime().exec("java -jar C:\\Users\\Cristian\\Desktop\\java\\numeros.jar \"" + entrada+"\"");
BufferedReader br = new BufferedReader(new InputStreamReader(proceso.getInputStream()));
String texto;
while((texto = br.readLine()) !=null){
if(Boolean.parseBoolean(texto)){
cerrado = true;
}else{
System.out.println(texto);
}
}
br.close();
proceso.destroy();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Child Process.
public static void main(String[] args) {
if(args.length <=0 && args[0].length() == 0){
System.out.println("No se ha introducido una entrada");
}else{
if(!args[0].equalsIgnoreCase("fin")){
System.out.println(Math.round(Math.random() * 10));
}else{
System.out.println("true");
}
}
}
}
Make your child process handling input stream:
public static void main(String[] args) throws Exception {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
while (!"fin".equals(line = reader.readLine())) {
System.out.println(line);
}
System.out.println("buy");
}
Then in main process you can send messages to child process:
Process proceso = Runtime.getRuntime().exec("java -jar C:\\Users\\Cristian\\Desktop\\java\\numeros.jar");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proceso.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(proceso.getInputStream()));
String texto;
out.write(entrada + "\n");
out.flush();
while((texto = in.readLine()) !=null){
...
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String className = "str.java";
String command = "javac " + className;
String output = obj.executeCommand(command);
System.out.println(output);// prints the output of the executed command
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
I am trying to compile a Java file (str.java) from another Java class(ExecuteShellComand.java). What I am trying to do is if "str.java" compiles successfully then I want to execute "java str" command, but if the compilation fails then proper stacktrace or errors should be printed. I am storing the stacktrace or the errors in output variable.
But when I execute this code although "str.java" has somes errors in it System.out.println(output) is not printing the errors.
If you want to capture the errors from a command then you shall capture error stream instead of Input stream
So replace
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
with
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
The Process class tries to mimetize OS process. It means, process keep different output stream for error and normal messages and one stream for input. In UNIX, should be:
wc < file > wc.count 2> wc.error
In Java...
abstract InputStream getErrorStream()
Gets the error stream of the subprocess.
abstract InputStream getInputStream()
Gets the input stream of the subprocess.
abstract OutputStream getOutputStream()
So, you should use getErrorStream() to get errors..
Refactoring your code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String className = "str.java";
String command = "javac " + className;
obj.executeCommand(command);
System.out.println(obj.output);
System.out.println(obj.errors);
}
private String errors;
private String output;
private void executeCommand(String command) {
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
errors = readStream(p.getErrorStream());
output = readStream(p.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private String readStream(InputStream inputStream) throws IOException {
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
return output.toString();
}
}
I'm running a Java program from another Java application using Runtime.getRuntime().exec like this
Process p1 = Runtime.getRuntime().exec("javac test.java");
Process p2 = Runtime.getRuntime().exec("java test");
The content of the test.java
import java.io.*;
class test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
}
}
I want to handle Input, Output and Error stream of the process p2.
I did capture of the output of the test.java, however, I do not know how to handle output and error.
Here is my code:
try {
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
bre.close();
p2.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception err) {
err.printStackTrace();
}
The code above works fine for capturing the output of the test.java. But it does not display error of the test.java.
Could you please give me a sample code for fixing this problem and handling output stream or share idea? Thanks in advance
The solution I've always used is to create a separate thread to read one of the streams
So, in your case it should be something like
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
new Thread(new Runnable() {
#Override
public void run() {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
}
}).start();
// when you are finished close streams