how to execute console commands in a java program for node - java

I need to access the console on the node through java
how to make this ?
public class Comando {
public static void main(String[] args) {
String comando = "C:\\Program Files\\nodejs\\node.exe";
try {
Process process = Runtime.getRuntime().exec(comando);
OutputStream stdin = process.getOutputStream ();
InputStream stderr = process.getErrorStream ();
InputStream stdout = process.getInputStream ();
stdin.write("1+2".getBytes());
stdin.flush();
// System.out.print(stdout.read());
stdin.close();
System.out.print(stdout.read());
//BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
// writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

I expect that node.exe requires text, not binary as you are using it.
This means that using PrintWriter to write lines of text and BufferedReader to read lines of text would make more sense.
Java has a built in Javascript interpreter. I assume you cannot use that for some reason.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
public class Comando {
public static void main(String[] args) {
String comando = "C:\\Program Files\\nodejs\\node.exe";
try {
ProcessBuilder builder = new ProcessBuilder(comando);
Process process = builder.start();
OutputStream stdin = process.getOutputStream();
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
stdout));
PrintWriter writer = new PrintWriter(stdin);
writer.write("1+2");
writer.flush();
stdin.close();
System.out.print(reader.read());// return -1
// writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It continues at me return -1, when I try read your output

Related

Java Writing to a file: does not write to all desired files

I am out of ideas, I've been trying for the whole day to separate one file which has a format of :
AN Aixas
AN Aixirivall
AN Aixovall
AN Andorra la Vella
BR Salto do Mandira
BR Salto do Norte
BR Salto Dollman
BR Salto Grande
BR Salto Pilao
...
and so one, into different files by the name of the Country "AA.txt" and to include all the cities in these separate files. But my program only writes to a certain bunch of files and I cannot figure out why.
I've tried all the writing files classes - same result.
Here is the result, all worked but on a certain bunch of files only.
Here is the code :
package com.fileorganizer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class File2 implements Cloneable {
static InputStream fis = null;
static BufferedReader br = null;
static String state = "";
static String tmp = "";
static File file = null;
static FileWriter fw = null;
static BufferedWriter bw = null;
public static void main(String[] args) {
int a = 0;
try {
fis = new FileInputStream(
new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/cities.txt"));
br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
state = line.substring(0, 2);
if (state.substring(0, 1).matches("^[A-Z]+$")
&& state.substring(1, 2).matches("^[A-Z]+$")
&& !tmp.equals(state)) {
file = new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/countriesFolder/"
+ state + ".txt");
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
tmp = state;
}
bw.write(line.substring(3) + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
}
}
I am really sorry for such a dumb question. Please help
You don't close bw anywhere, so the contents in the BufferedWriter's buffer are lost.

compiling java file from another java class

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

No value is writtern in my tcp client/server program

In my TCP socket program I have to send data from client to server. In server side I have to read the streams and write it in file. But File is created and nothing is written inside.
Client side coding to send file:
try
{
Socket ss = new Socket("localhost", 5010);
BufferedOutputStream put = new BufferedOutputStream(ss.getOutputStream());
BufferedReader st = new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f = new File("e://read.txt");
FileInputStream fis = new FileInputStream(f);
byte buf[] = new byte[1024];
int read;
while((read = fis.read(buf, 0, 1024)) != -1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
Server to read the inputstream and write it in a file:
try
{
ServerSocket ss = new ServerSocket(5010);
Socket s = ss.accept();
BufferedReader get = new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata = new FileWriter("c://write.txt");
BufferedWriter bw = new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
What is the problem?
You forgot bw.close and bw.flush....below is the code that works...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(5010);
Socket s=ss.accept();
BufferedReader get= new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata=new FileWriter("c://Test//testoutput.txt");
BufferedWriter bw=new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
bw.flush();
bw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class TestClient
{
public static void main(String[] args)
{
try
{
Socket ss=new Socket("localhost",5010);
BufferedOutputStream put=new BufferedOutputStream(ss.getOutputStream());
BufferedReader st=new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f=new File("c://Test//testinput.txt");
FileInputStream fis=new FileInputStream(f);
byte buf[]=new byte[1024];
int read;
while((read=fis.read(buf,0,1024))!=-1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Don't use Readers and Writers unless you know that the data is text. Use InputStreams and OutputStreams, and copy them so:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
in.close();
Use this logic in both the client and the server.
Notes:
It is counterproductive to put a flush() inside that loop.
If buffer is greater than 4096, which it should be, it is pointless to use a BufferedInputStream.

Error in File I/O

I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()

Process requires redirected input

I have a UNIX native executable that requires the arguments to be fed in like this
prog.exe < foo.txt.
foo.txt has two lines:
bar
baz
I am using java.lang.ProcessBuilder to execute this command. Unfortunately, prog.exe will only work using the redirect from a file. Is there some way I can mimic this behavior in Java?
Of course,
ProcessBuilder pb = new ProcessBuilder("prog.exe", "bar", "baz");
does not work.
Thanks!
ProcessBuilder pb = new ProcessBuilder("prog.exe");
Process p = pb.start();
OutputStream pos = p.getOutputStream();
InputStream fis = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int read = 0;
while((read = fis.read(buffer)) != -1) {
pos.write(buffer, 0, read);
}
fis.close();
Not tested, but something like this should work.
I ended up doing something like this and it works. Thanks for all the help!
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
public class UserInp {
public static void main(String[] args) {
new UserInp().sample();
}
public void sample() {
String command = "foo.exe";
List<String> args = new LinkedList<String>();
args.add("bar");
args.add("baz");
ProcessBuilder pb = new ProcessBuilder(command);
java.lang.Process process = null;
try {
process = pb.start();
} catch (IOException ex) {
//--
}
OutputStream os = process.getOutputStream();
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
final InputStream is = process.getInputStream();
new Thread(new Runnable() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (java.io.IOException e) {
}
}
}).start();
for (String arg : args) {
pw.println(arg);
}
pw.close();
int returnCode = -1;
try {
returnCode = process.waitFor();
} catch (InterruptedException ex) {
//--
}
System.out.println(returnCode);
}
}
The redirection is setup by the shell you need todo this manually, something like that:
Process proc = pb.start();
OutputStreamWriter os = new OutputStreamWriter(proc.getOutputStream());
// then write the data from your file to os
// ...
os.close();
Did you try to wrap prog.exe into a script which accepts arguments and deal with prog.exe ?
I assume you're using a shell, so it's quite simple to set up a bash script.
If I understand your problem, the script would look like :
#!/usr/bin/bash
echo $1 > file
echo $2 >> file
prog.exe < file
remove file
Build the process using a ProcessBuilder, then use process.getOutputStream() to get an OutputStream that will pipe to the standard input of the process.
Open the file using normal Java techniques, read the contents of the file and write it to the OutputStream going to the Process you made with the ProcessBuilder.
The problem you have right now is that you're calling the ProcessBuilder to launch
$ prog.exe foo bar
Which is probably nothing close to what you want to achieve.

Categories

Resources