The following code(when executed) prompts the user to enter any java class name to execute.
import java.io.*;
public class exec {
public static void main(String argv[]) {
try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the java 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();
}
}
This code works fine if I'm using command prompt and I'm able to execute another java program. But I'm unable to do the same using eclipse.No output or error is showing up once I enter the java class name.
I'm new to eclipse. Need help.
You can't "execute" a java class, so your code as posted can't work.
Instead, you'll need to execute "java" and pass to it the classpath and class name as parameters, something like this:
String s = br.readLine();
String[] cmd = {"java", "-cp", "/some/path/to/your/jar/file", s};
Process pro = Runtime.getRuntime().exec(cmd);
Do you just enter the name of the class, or do you also enter the directory of where the program is located? I think it doesn't work in eclipse because you need to specify where the file is... like C:\Users\Me\workspace\ProjectName\src\filename
Related
So I'm trying to practice connecting out of one java program to the input of another program and I'm wondering if the way I did it is efficient or if there's a better way. I'm saving a string into a text file in the first program and reading the string then printing it out in the second. Is there a way to just cut out using the text file as a middle man?
Here's my first program:
import java.util.Scanner;
import java.io.*;
public class pip1{
public static void main(String[] args){
String inString = "";
Scanner sc = new Scanner(System.in);
inString = sc.next();
try{
PrintWriter out = new PrintWriter("word.txt");
out.println(inString);
out.close();
} catch(FileNotFoundException ex){ }
}
}
and here is the second:
import java.io.*;
public class pip2{
public static void main(String[] args) {
String fileName = "word.txt";
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String outString = br.readLine();
br.close();
fr.close();
System.out.println(outString);
} catch (FileNotFoundException ex) {}
catch (IOException ex) {}
}
}
Thanks!
I suppose what you want is a pipe, which acts as a "intermediate wire" between two processes without using an "temporary file".
So I recommend you to read doc about Pipes in JAVA.
Here's a link of tutorial.
Also see javadoc about PipedInputStream
javadoc about PipedOutputStream
What's more, if your OS supports IO redirection from terminal, then just do it without using , as Andy says. This would be the easiest.
Just write to System.out in the first one, read from System.in in your second, and use a pipe to connect the output of the first into the second when you run the two commands:
java pip1 | java pip2
I want to write a program which executes JARs and gets their output.
When the JAR program has only a print statement it works fine, but when it asks for input during execution, the program freezes.
Code of the JAR file program:
import java.util.*;
public class demo {
public static void main(String r[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Hello ...");
System.out.println("please enter the number :");
int i = sc.nextInt();
System.out.println(" number : " + i);
}
}
Code of the original program which runs the JAR files:
public class jartorun {
public static void main(String arg[]) throws IOException {
String t = "javaw -jar D:\\jarcheck\\temp.jar";
Process p = Runtime.getRuntime().exec(t);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.print(line + "\n");
}
input.close();
}
}
I can give input to the JAR using process.getOutputStream(), but how would I use it so I can create a program which can give input to a JAR and read its output simultaneously?
If you want to run stuff outside the VM use the ProcessBuilder. Works fine for me and you can inherit the IO Stream.
ProcessBuilder builder = new ProcessBuilder("./script.sh",
"parameter1");
builder.directory(new File("/home/user/scripts/"));
builder.inheritIO();
try {
Process p = builder.start();
p.waitFor();
// Wait for to finish
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
This should also work with Windows batch scripts and paths.
(haven't tried the input though)
You can use p.getOutputStream() to provide input to the launched process.
I am a beginner Java programmer, and I use this Java Tutorial.
In the I/O from the Command Line page, it uses InputStreamReader cin = new InputStreamReader(System.in); to get user input from the command line. But when I try to use it, nothing happens. I have a very simple program, and it's just to test whether this works, but it doesn't.
import java.io.*;
public class TestInput {
public static void main(String args[]) {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
if(cin.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}
}
It just says, "hello, guest" and exits, without letting me input anything.
I'm assuming this is supposed to work similar to System.console, but if this isn't what it's supposed to be like, please tell me.
What is wrong with my code?
thanks for any answers.
EDIT
From the edits I'm getting, I suppose I have to use cin.readline() to actually read the input.
I got my program to work. thanks!
try{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String name= cin.readLine();
if(name!=null && name.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}catch(IOException e){
}
You have to read the input:
if(cin.readLine().equals("jon")) { // or "jon".equals(...) to handle null
(See BufferedReader.readLine())
You will also have to handle the potential IOException with a try-catch.
With cin.equals("jon"), you are testing if the BufferedReader object cin is itself equal to the string "jon", which is clearly false.
You need to use, cin.readLine()
Oracle Docs.
if(cin.readLine().equals("jon"))
Also, you need to handle the IOException
Im facing this strange issue of not being able to execute a simple "whoami" unix command on a AIX server. I have a webapplication that is deployed on an AIX server. Now I want to see under which WAS user my webapplication is currently running. So I added the below code:
public String whoami() throws Exception {
Process p = Runtime.getRuntime().exec("whoami");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String output = "";
while ((line = in.readLine()) != null) {
//System.out.println(line);
output += line;
}
in.close();
p.destroy();
return output;
}
}
The above code is added in a jar file which is referred by a JSP. The JSP has to receive the output of the code above and it displays the WAS User name. But when i deploy the webapplication on the server and try to observe the output, im getting an error message like
Error 500: access denied (java.io.FilePermission <> execute)
However, When I remove the above code and run my webapplication, everything runs fine. What wron am i doing here. Did I miss doing anything? Please help. This is the first time im working on UNIX
It looks like your web server has been configured with a Java security policy that prohibits executing external applications.
See http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html for information about Java Security Policies, and the documentation for your web server.
You will need to supply (or edit) a policy file to contain something like:
grant {
permission java.io.FilePermission
"/usr/bin/whoami", "execute";
};
Just out of curiosity
Have you considered to use:
user.name
System property in Java?
AFAIK whoami is a shell command and Runtime#exec() executes programs only.
you can try Runtime.getRuntime().exec(new String[]{"sh","-c","whoami"}) to call sh and let it execute whoami
another thing: do you need to destroy the process after reading?
You can use the ProcessBuilder class instead of getRuntime().exec("whoami").
Here is sample code
import java.io.*;
import java.util.*;
public class DoProcessBuilder {
public static void main(String args[]) throws IOException {
if (args.length <= 0) {
System.err.println("Need command to run");
System.exit(-1);
}
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
I'm using Runtime.getRuntime().exec in eclipse to run another java program from the current program.
I've used the following code.
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the class name");
String s=br.readLine();
String str="XYZ";
String[] cmd = {"java","-cp", "C:/Users/..../workspace/Testing/bin",s,str};
Process pro=Runtime.getRuntime().exec(cmd);
I'm also passing a string "XYZ" to that program. That program just accepts the string and displays
Your string is XYZ
But by using the line
String[] cmd = {"java","-cp",
"C:/Users/..../workspace/Testing/bin",s,str};
i'm able to run the program but it is not accepting any arguments. It is neither displaying the output nor showing any errors.
Where am i going wrong?
Consider the program to be called is
import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter any string");
String s=br.readLine();
System.out.println("Your string is "+s);
}
}
This program should accept the string XYZ and prints Your string is XYZ
You need to read the output (and error) streams from the Process using getInputStream() and getErrorStream(). You’ll need a separate thread for this if you want to wait for the process to complete.
String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
final InputStream pOut = p.getInputStream();
Thread outputDrainer = new Thread()
{
public void run()
{
try
{
int c;
do
{
c = pOut.read();
if (c >= 0)
System.out.print((char)c);
}
while (c >= 0);
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
outputDrainer.start();
p.waitFor();
If you are using Java 7 and want all output of the process to be redirected to the console, the code is considerably simpler:
String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectError(Redirect.INHERIT)
.redirectOutput(Redirect.INHERIT)
.start();
p.waitFor();
The redirectError() and redirectOutput() methods with Redirect.INHERIT cause output to just be sent to the parent Java process.
You are executing javac, the language compiler. I believe you want to invoke the java runtime on the class file with your main method. Replace javac with java, and specify your main class.
You are passing your data as an Argument but reading it from System.in. If you read the data from the arguments it'll work. So do what #prunge said to capture what the subprocess print and use this as your test and everything will work just fine.
import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException
{
if(args.length==0)
System.out.println("No String received");
else
System.out.println("Your string is " + args[0]);
}
}
Be sure that you check both the InputStream and the ErrorStream.
If you however want to pass the data via System.in then you have to change your call code to:
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the class name");
String s=br.readLine();
String str="XYZ";
String[] cmd = {"java","-cp", "C:/Users/..../workspace/Testing/bin",s};
Process pro=Runtime.getRuntime().exec(cmd);
PrintWriter output= new PrintWriter(pro.getOutputStream());
output.println(str);