Write to and read from the Windows Command Prompt by Java - 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();
}
}

Related

how to feed multipe files to command line in java without using shell

I am quite new to java, so it might be a stupid question. But I need it to be solved for my data structure class project...
So I am trying to feed my program with 2 different input files. I know we can use Scanner and InputStreamReader to achieve this with 1 file, I don't know how I should do it with 2 files.
In some answers to similar questions with mine, someone mentioned shell which I think can probably solve this problem. However, I don't know anything about shell, so I am wondering if this problem can be solved without writing a shell file, and what the syntax would be for inputting multiple files in command line.
What I execute in command line(with 1 input file):
java UserInterfaceOrNot < input.txt > output.txt
I will post more code if needed.
Code:
public class UserInterfaceOrNot
{
public static EventManager em;
public static Scanner scn = new Scanner(new InputStreamReader(System.in));
public static void main (String [] args)
{
UserInterfaceOrNot ui = new UserInterfaceOrNot();
while (scn.hasNext()){ui.runData();}
scn = new Scanner(new InputStreamReader(System.in));
while (scn.hasNext() && !scn.next().equals("x")){ui.runCommand();}
}
java UserInterfaceOrNot input1.txt input2.txt output.txt
When you call your program as this, you're actually passing 3 arguments to your java public static void main (String [] args) method.
You can find these argument in order in that String array (String [] args).
To read the arguments:
String myFirstFile = args[0]; // this will be "input1.txt"
String mySecondFile = args[1]; // this will be "input2.txt"
String myOutputFile = args[2]; // this will be "output.txt"
You can read each file (input1 and input2) like this by creating another method
public String readFileAsString(String inputFile) throw IOException {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
Then in your main method you can call it like this:
public static void main(String[] args) throws Exception {
UserInterfaceOrNot ui = new UserInterfaceOrNot();
String inputFile1 = args[0];
String inputFile2 = args[1];
String input1AsString = ui.readFileAsString(inputFile1);
String input2AsString = ui.readFileAsString(inputFile2);
//continue with your logic
}

Search for a specific word when reading a --traceroute command in java code using bufferreader

I am trying to search the word "hop" from the traceroute output, but somehow its not displaying that line on console. Please let me know where I am going wrong.
Here is my code:
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
String[] cmdarray = { "nmap", "--traceroute", "nmap.org" };
Process p = Runtime.getRuntime().exec(cmdarray);
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
if (line.contains("hop")) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
A few things:
Are you running this in Linux? If you are, you have to run nmap as root. Are you doing so?
I'm not exactly sure what you're trying to look for. In my run of nmap --traceroute nmap.org, there were no lines that contained the word "hop" in lowercase. So even if you are running this program as root, you probably aren't getting very much. I'm fairly certain it doesn't print the word "hop" in lowercase on Windows, either.

How do I only send the output and not the input to InputStreamReader when executing a shell command using ProcessBuilder?

I am executing an executable with a command line argument using ProcessBuilder and I am trying to read the output using a BufferdReader. However, when I print out the input stream of the process, it seems I am first printing out the output, then the input as well.
For example, I am trying to execute "my_command -an-option /path/to/file", and when I print out the buffered reader, I am printing out the output followed by the contents of the my file at /path/to/file. I guess it makes sense that the input stream is reading in my inputp and the output,
public static void d(String file) throws Exception {
ProcessBuilder builder = new ProcessBuilder("my_command", "-an-option", file);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
process.waitFor();
String s = null;
while ((s = in.readLine()) != null) System.out.println(s);
in.close();
}
public static void main(String[] args) {
d("/path/to/file");
}
Does anyone know how to make it only print out the output? I want to save the output to a string or something and parse it, etc.

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...
}

Passing values from one java program to another

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/

Categories