Passing values from one java program to another - java

I wrote a Java program that can execute another Java program during runtime. The program is as follows:
import java.io.*;
public class exec {
public static void main(String argv[]) {
int i = 5, j = 6, k = 7;
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter class name");
String s = br.readLine();
Process pro = Runtime.getRuntime().exec(s);
BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line=null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch(Exception err) {
err.printStackTrace();
}
}
}
If I execute this program it will prompt the user to enter any class name (Java program) to execute. This is being done using this piece of code Process pro=Runtime.getRuntime().exec(s);.
Once the user enters the Java class name, I should be able to pass the values 5,6,7 to the Java class entered by the user. Only one value at a time should be passed and the square of that number should be calculated.
How can I do this?

You can pass the int argument to your second Java program as follows:
String[] cmd = { s, Integer.toString(n) };
Process pro=Runtime.getRuntime().exec(cmd);
... or as a single String:
Process pro=Runtime.getRuntime().exec(String.format("%s %d", s, n);

In the second program you can implement a Server Socket then in your first program you can write a Client Socket which sends messages to second application.
You can see the following documentation: http://download.oracle.com/javase/tutorial/networking/sockets/

Related

Start cmd.exe on new Process then user Scanner on it

Is there a way to open a cmd.exe via ProcessBuilder and then reference its streams such that one could call NewProcessOutputStream.println() and Scanner s = new Scanner(NewProcessInputStream)?
I am aware that I can issue a command such as cmd /c dir and read the input stream, but I would like to open the cmd process, then access its streams such that I can print to it whenever.
Is what I am thinking of possible? Or should I be executing another program via the process?
Edit (Updated): Output not what expected
import java.io.*;
import java.util.*;
public class Terminal {
public static void main(String[] args) throws IOException {
Process cmd = new ProcessBuilder("cmd").start();
PrintWriter writer = new PrintWriter(cmd.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
writer.println("Hello");
writer.println("World!");
writer.println("How are you?");
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Output:
C:\Users\Paul\Desktop\temp\CLI\src>java Terminal
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\Users\Paul\Desktop\temp\CLI\src>Hello
C:\Users\Paul\Desktop\temp\CLI\src>World!
C:\Users\Paul\Desktop\temp\CLI\src>How are you?
C:\Users\Paul\Desktop\temp\CLI\src>
C:\Users\Paul\Desktop\temp\CLI\src>
Yes, you can get the process input using Process.getOutputStream() and its output using Process.getInputStream().
Here's an example:
public class ProcessTest {
public static void main(String[] args) throws IOException {
Process grep = new ProcessBuilder("grep", "foo").start();
PrintWriter writer = new PrintWriter(grep.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(grep.getInputStream()));
writer.println("this is the first line");
writer.println("this is the foo line");
writer.println("this is the last line");
writer.println("nope, another foo");
writer.close();
// EDIT: fixed end of stream check
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
}

Write to and read from the Windows Command Prompt by Java

I need to make a simple Java program that writes it output to the cmd (the Command Prompt) window and reads user's input from there.
When I run the code from the IDE using the standard System.out.println it presents the output on the IDE (I use intelliJ) console view.
I guess this is a simple question and there are already answers for it here but I made several searches and did not find appropriate resolution.
That's it. your program now will output to cmd if you run it using cmd instead of IDE.
For input you can use scanner to read user input. or simply let user enter them all before running the program and include the args of main method in your logic to process user's input.
demo for u :)
public class testCMD {
public static void main(String[] args) {
testCMD obj = new testCMD();
System.out.println("Press command here:");
Scanner keyboard = new Scanner(System.in);
String command = keyboard.next();
//String command = "msconfig";
String output = obj.executeCommand(command);
System.out.println(output);
}
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();
}
}

BufferedReader not working as expected

The below code is not getting executed completely after this line " bufferedReader.readLine(); ". The Program works fine when i execute the system command with
out mentioning IPAddress of the remote PC.
class Test
{
public static void main(String arg[])
{
Process p;
Runtime runTime;
String process = null;
try {
runTime = Runtime.getRuntime();
p = runTime.exec("sc \\xx.xx.xx.xx query gpsvc"); // For Windows
InputStream inputStream = p.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
process = "&";
while (line != null) {
line = bufferedReader.readLine();
process += line + "&";
}
StringTokenizer st = new StringTokenizer(proc, "&");
System.out.println("token size "+st.countTokens());
while (st.hasMoreTokens()) {
String testData = st.nextToken();
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
}
} catch (IOException e) {
System.out.println("Exception arise during the read Processes");
e.printStackTrace();
}
}
}
Check your command inside exec method
p = runTime.exec("sc \\xx.xx.xx.xx query gpsvc");
The syntax is wrong here and if you execute this from command prompt, you will be prompted with the below question.
Would you like to see help for the QUERY and QUERYEX commands? [ y | n ]:
And the program wouldn't return until you enter y or n. Since the program is not terminating, you wouldn't be able to read the console output and that's the reason your program is getting stuck on String line = bufferedReader.readLine();

Handling Java command line arguments in the format “cat file.txt | java YourMainClass”

I've never used java from the terminal before, and I certainly have never coded for it. My question is simple: How do I intake a file when the calling format is
cat  file.txt  |  java  YourMainClass
I have the rest of the code up and running swimmingly, I just need to take the given file name into my main method.
Since the cat command displays the contents of the file, you need to use the System.in buffer to capture the data coming in from that command. You can use a BufferedReader pointing to System.in to loop through the data and process it.
Look at this Example
public class ReadInput {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String x = null;
while( (x = input.readLine()) != null ) {
System.out.println(x);
}
}
}
As you are looking to read from System.in as the output from cat, you could do:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
// use line...
}

java program Inetaddress

The question I have been asked is too
write java program that reads IP address from input file and writes the corresponding host names in the output file and vice versa.
here is my code:
import java.net.*;
import java.io.*;
public class hw
{
public static void main(String args[])
{
try{
FileReader f= new FileReader("w.txt");
BufferedReader r = new BufferedReader(f);
FileWriter o = new FileWriter("out.txt");
PrintWriter p = new PrintWriter(o);
String line = r.readLine();
String hn=line;
String IP;
InetAddress d=InetAddress.getByName(hn);
while(line !=null)
{
hn=d.getByName(line);
p.println(hn);
IP=d.getHostName();
p.println(IP);
}
r.close();
p.close();
}
catch(FileNotFoundException e )
{System.out.println("file not found");}
catch(IOException e)
{System.out.println("io error "+e.getMessage());}
}//main
}//class
I guess your while loop never terminates. Usually I read in a loop like this:
while ((line = r.readLine()) != null) {
// process line, i.e.
InetAddress ia = InetAddress.getByName(line.trim());
// etc.
}
Also you might consider putting your close statements into the finally block for good form.
kevin corrected your loop error , as for your second question
I suggest you read this tutorial about reading and writing files Using stream io

Categories