PDA

View Full Version : how to redirect in java



srujanabobba
6th August 2006, 02:32 PM
Hai friends,
i want to execute a shell command in java.. so i executed the below program..
i am getting the output when i gave ls but it is not working when i am giving ls >abc.txt

this is the program:

import java.util.*;
import java.io.*;

// class StreamGobbler omitted for brevity
class StreamGobbler extends Thread
{
InputStream is;
String type;
OutputStream os;

StreamGobbler(InputStream is, String type)
{
this(is, type, null);
}

StreamGobbler(InputStream is, String type, OutputStream redirect)
{
this.is = is;
this.type = type;
this.os = redirect;
}

public void run()
{
try
{
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os);

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null)
pw.println(line);
System.out.println(type + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}


public class TestExec
{
public static void main(String args[])
{


try
{
String cmd ="ls -l " ;
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERR");

// any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "");

// kick them off
errorGobbler.start();
outputGobbler.start();

// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}


Now,i want to redirect the output i get from ls command to some file...
is it possible??
Help me please.

srujanabobba
6th August 2006, 04:54 PM
i got it.
May be some other person may need this.So, i am posting how to do it here.

instead of giving cmd="ls > something.txt" in the program
give

String[] cmd={"sh","-c","ls >something.txt"};

It worked for me...

byeee