Java - How to send a value to child process using outputstream? - java

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){
...

Related

Reading file contents as input into console

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());
}
}
}

Make a Server wait for input from two different controllers

I made a client-server application where the server has to send a list of emails to the client, which after load that into a ListView gives the possibility, through a menuBar, to delete them. In the client all these operations are made in the Data Model (I followed the MVC pattern). This is the server:
class ThreadedEchoHandler implements Runnable {
private Socket incoming;
private String nomeAccount = "";
public void run() {
try {
incoming = s.accept();
} catch (IOException ex) {
System.out.println("Unable to accept requests");
}
contenutoTextArea.append("Connected from: " + incoming.getLocalAddress() + "\n");
textarea.setText(contenutoTextArea.toString());
try {
//PHASE 1: The server receives the email
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
nomeAccount = in.readLine();
} catch (IOException ex) {
System.out.println("Not works");
}
//PHASE 2: I'm getting all the emails from the files
File dir = new File("src/server/" + nomeAccount);
String[] tmp = new String[100];
int i = 0;
for (File file : dir.listFiles()) {
if (file.isFile() && !(file.getName().equals(".DS_Store"))) {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
tmp[i++] = line;
}
} catch (IOException ex) {
System.out.println("Cannot read from file");
}
}
}
//PHASE 3: The server sends the ArrayList to the client
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
for (int j = 0; j < i; j++) {
out.println(tmp[j]); // send the strings to the client
}
} catch (IOException ex) {
System.out.println("Cannot send the strings to the client");
}
//PHASE 4: Here I loop and wait for the client choise
BufferedReader in;
String op;
try {
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
while ((op = in.readLine()) != null) {
if (op.equals("Elimina")) {
String tmp = in.readLine();
File file = new File("src/server/" + nomeAccount + "/" + tmp + ".txt");
file.delete();
} else if (op.equals("Invia")) {
//...
} else {
//...
}
}
} catch (IOException ex) {
System.out.println("Non so");
} finally {
try {
incoming.close();
} catch (IOException ex) {
System.out.println("Cannot closing the socket");
}
}
}
}
These are the methods of the client:
public void loadData() throws IOException, ClassNotFoundException, ParseException {
try {
s = new Socket("127.0.0.1", 5000);
ArrayList<Email> email = new ArrayList<Email>();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date data;
/* PHASE 1: The client sends a string to the server */
//try {
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println(account); // send the account name to server
/* PHASE 2: The client receives the ArrayList with the emails */
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
String message[] = new String[5];
for (int j=0; (line = in.readLine()) != null;) {
message[j++] = line;
if (j==5) {
data = format.parse(message[3]);
email.add(new Email((Integer.parseInt(message[0])), message[1], account, message[2], message[4], data));
j=0;
}
}
//Casting the arrayList
emailList = FXCollections.observableArrayList(email);
//Sorting the emails
Collections.sort(emailList, (Email o1, Email o2) -> {
if (o1.getData() == null || o2.getData() == null) {
return 0;
}
return o1.getData().compareTo(o2.getData());
});
/*} finally {
s.close();*/
//}
} catch (SocketException se) {
emailList.setAll(null, null);
}
}
public void deleteMail(Email da_elim) throws IOException {
int id_del = da_elim.getID();
emailList.remove(da_elim);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Elimina");
out.println(id_del);
}
The PHASE 1, 2, 3 of the Server are for the upload of the emails, and work with the loadData() method. Without the PHASE 4 the program works. Now, if I write that loop, the GUI of the client doesn't load and I cannot press on the DELETE button (which should make the input to innescate something (in this the elimination of the file) into that loop. Why the client doesn't load even if they are two different threads? And why without that loop it works?
EDIT: with the Listener class implemented but still doesn't works
//PHASE 4: Here I loop and wait for the client choise
BufferedReader in;
String op;
try {
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
/*while ((op = in.readLine()) != null) {
System.out.println("OP: " + op);
if (op.equals("Elimina")) {
String tmp = in.readLine();
contenutoTextArea.append("Ho eliminato la mail ").append(tmp).append(" \n");
textarea.setText(contenutoTextArea.toString());
File file = new File("src/server/" + nomeAccount + "/" + tmp + ".txt");
file.delete();
}
}*/
Listener lis = new Listener(in, new LinkedBlockingQueue<String>());
lis.run();
System.out.println("bbbbb");
} catch (IOException ex) {
System.out.println("Unable to read messages");
} finally {
try {
incoming.close();
} catch (IOException ex) {
System.out.println("Cannot close the socket");
}
}
I think you should run jvisualvm (it's a tool installed with jdk in /bin/ location of your jdk) and look for that Thread lifecycle you create on server. Also check if your Thread don't go through the code and just ends his life skipping waiting for client.
Is this Thread somehow connected with client? Because you cannot run client App. Are they separated? Another think that came to my mind is using
Platform.runLater(()->{
});
if your client GUI is in JavaFX. Use it if you are creating GUI, changing values in fields and anything you do on your GUI. Maybe your server is waiting for user response and after that GUI is built? Which causes that you can't press DELETE button.
I'm not currently able to comment, so I can't ask for clarification, but I think I'm correctly interpreting what's wrong. "The program hangs when it enters a loop that waits for input from two controllers". Assuming I got that part right, the most likely culprit would be that buffered reader is hanging indefinitely because its not receiving input. When I first ran into this issue, I threw it inside its own "receiver" class and used a Queue to bus over anything it received to a loop in my main class. my code looked something like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
public class Listener implements Runnable
{
private BufferedReader br;
private BlockingQueue<String> q;
private boolean shouldClose = false;
public Listener(BufferedReader br, BlockingQueue<String> q)
{
this.q = q;
this.br = br;
}
public void run()
{
loop();
System.out.println("listener has stopped");
}
public void loop()
{
String line = "";
try
{
while((line = br.readLine()) != null && !shouldClose)
{
q.put(line);
}
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
}
public void shutdown()
{
shouldClose = true;
}
}
apologies if I've misunderstood in any way, or missed something in your code.

Program outputs code from multiple methods instead of just one method

I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.
Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).

Socket server stuck

I'm trying to make a server/client to send text from client to server then sending back an ok message or something similar back to the client, but for some error that I can't see, either the server gets stuck right before sending the ok back to the client, or the client does not receive the message (I think it's the first one though).
Any help is appreciated.
This is the server code:
class ActiveServer extends Thread {
InputStream inStream;
OutputStream outStream;
public ActiveServer(InputStream inStream, OutputStream outStream) {
this.inStream = inStream;
this.outStream = outStream;
}
#Override
public void run() {
boolean ret = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
PrintWriter writer = new PrintWriter(outStream);) {
String line = null;
while((line = reader.readLine()) != null) {
String[] str = line.split(";");
line = null;
switch (str[0]) {
case "insert" : //ret = SQLOptions.insert(str[1], str[2]);
System.out.println(str[1]);
break;
}
writer.print(ret);
writer.flush();
// As far as i can see it gets stuck at the end of this while, but I don't know why.
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Server {
private static final int PORT = 39165;
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(PORT);) {
System.out.println("Servidor online");
ExecutorService service = Executors.newFixedThreadPool(10);
while (true) {
Socket client = server.accept();
InetAddress ip = client.getInetAddress();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date time = new Date();
System.out.print(sdf.format(time));
System.out.println(" " + ip + " connected");
InputStream inStream = client.getInputStream();
OutputStream outStream = client.getOutputStream();
service.execute(new ActiveServer(inStream,outStream));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here goes the client code:
public class Telnet {
static Console console = System.console();
public static void connect(String ip, String port) {
try(Socket socket = new Socket(ip, Integer.parseInt(port));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
String msg = null;
while(true) {
msg = console.readLine();
writer.println(msg);
writer.flush();
if (msg.equals(".quit")) {
System.out.println("Exiting...");
break;
}
String input = reader.readLine();
System.out.println(input);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if(args.length < 2) {
err.println("Telnet <ip> <port>");
return;
}
if (console == null) {
err.println("A console is not available");
return;
}
connect(args[0], args[1]);
}
}
On the server side, you write the response without a terminating newline:
writer.print(ret);
But on the client side, you read until the end of line:
String input = reader.readLine();
The documentation for BufferedReader#readLine says:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Thus, the client will wait forever for the newline sequence which the server will never send.

capture error from runtime process java

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

Categories

Resources