Using redirection operator ( ) in Runtime.exec()

I am trying to execute a command "cat abc.txt > 123.log" from my Java program using Runtime.exec(). However, the exec() command isnt able to interpret ">" as an operator, instead it uses this as a string. Any suggestions on how I can run the above command using exec()???

hi hiwa,
could u tell me, why dont this
e, why dont this program is not clearing the screen
in linux. though some commands are working like
"poweroff", "reboot"..
public class ExecuteCommand{
public static void main(String[] args) throws
ws Exception{
String[] cmd = {"sh","-c","clear"};
//String cmd = "clear";
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
Commands like "poweroff" and "reboot" work on underlying system while "clear", "cd" etc.
work on current shell. Current shell is the shell on which we have invoked java command.
But the shell java runtime invokes is not(can't be) current shell but its child, a sub-process.
Thus we don't see current shell window cleared by a java runtime program.

Similar Messages

  • Don't redirect output or Runtime.exec()

    Hello, I am using Runtime.exec() to execute a .bat file on a windows xp machine. I am able to read the output within the java app just fine. The problem is that I don't want the output to be redirected to a java stream as the default behavior of Runtime.exec() enforces. Is there anyway to run a .bat file and have the output stay in the DOS window that appears?

    Thanks for the input so far. Here is more detail. I have to execute the bat file. No way around that one. I tried getting no window to pop up but the only solution I found to this was to create a shortcut and launch the process with a minimized window. Not to keen on this solution as it isn't very elegant. Plus it would be very very bad if the window was closed in the middle of execution. If anybody knows of a better way not to have the window show up I would like to hear it.
    So now I am stuck with a blank DOS window. I figure the next best thing is to just use the window and have the output that normally shows up there to actually show up there when launched from a java process. This way hopefully the user realizes something is running in the window and they shouldn't close it.
    You would think java would have some way to a launch a process and forget about it.

  • Problem to execute cvs command using Runtime.exec method

    Hello,
    I want execute this cvs command, with this options:
    cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
    I tried to execute with Runtime.exec() :
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
    How I can do to use this command with Runtime.exec ?
    Thanks.
    Regards.

    Sorry,
    I had a typing mistake.
    I want say:
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    Regards.

  • Runtime Exec and ProcessBuilder

    I have an object (textTicket) which is a formatted transaction label. Here is an example:
    CROSS PLAINS QUARRY CROSS PLAINS TN 37049 2549
    MATL SPREADING NOT GUARANTEED
    615-654-9942 TOLL FREE 877-654-9942
    Date: 01/19/2009 04:45:46
    Job No: PU-2008
    Q Num::
    Cust No: 30000001 Src Num::
    Sold To: CASH SALE
    Address: INTERNAL
    NASHVILLE,TN 37202
    Ord By:
    Ord No: Rate Zone:
    Location:THANKS YOU
    Mat. & Haul170.28 Sev Tax:0 Tax16.60
    Acc Total:1308.16
    Total186.88
    3/4 TO 4/67'S
    Gross: 40500 St. Item:
    Tare: 12120 P.O.: MIKE MILLER
    Net: 28380.0
    Net Tons: 14.19
    Proj:
    Truck #: 1
    Hauler: Phy Truck: 248251
    I am attempting to pass this textTicket object to a shell script that will send it out the port for printing. I have tried using the Java Comm API however, we have intermittent problems with the API running on an Oracle Appserver. Sometimes, the data never gets sent to the port. So what I am trying to do is just call a shell script that echos the textTicket out the port via redirection. The problem arise when I use the ProcessBuilder or runtime exec and I have to convert the textTicket to a string via textTicket.toString. The textTicket then losing all of its formatting. Any ideas on how to keep the formatting as I am passing the textTicket to the shell script.

    My example did not save into the post very well. For instance, the first line "Cross Plains Quarry" should be center on the paper. The object contains \t\t to get it center.
    For example on the runtime.exec, I am doing the following
    public void printShell(String port, String string){
         String[] params={"/usr/ts/bin/prttick.sh", string, port};
         try {
                   Process p=Runtime.getRuntime().exec(params);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   SerialCommunicator.logger.debug("error" + e.getMessage());
    The variable string is textTicket.toString();

  • Runtime.exec() and fork() and Process

    So let me see if I understand this correctly, and if I don't please fill me in. If I call the following piece of codeRuntime.getRuntime().exec("chgrp rcsweb " + path+fs+orgName);
    Runtime.getRuntime().exec("chmod 660 " + path+fs+orgName);where path is the real path to a file, fs is short for File.spearator and orgName is the name of a file, then in the Unix environment, it will fork off a process.
    First, I seem to remember one forum topic that mentioned not forgetting about killing the process returned by exec, so I guess I need to add that to my code.
    Second, since I am forking off this process inside of a J2EE container, am I actually forming off the entire container, or just the Servlet where Runtime is called, or what?
    Third, how can I prevent the error java.io.IOException: Not enough space
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:54)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)when I do not have the option of changing my VM size? Is killing the Process (and using waitFor()) going to take care of this issue?
    I appreciate your help.

    OK, after writing a few test programs, it is indeed clear..on unix (at least on solaris) when calling runtime.exec(..) The ENTIRE VM does indeed get forked. Therefore if your current Memory allocation for you VM is sitting at say 64MB (or you initial memory setting), another 64MB process will be created, even if you doing something as a simple
    exec("ls");
    I also tried putting runtime.exec call in its own thread hoping that if it was not in the main thread, that only that process would be forked..to no avail..the entire vm is indeed forked everytime...making runtime.exec damn near useless for server side work, and very dangerious..as you can essentialy assume you always need 2x your memory requirements.
    If anyone has figured out a workaround...any suggestions greatly appreciated.
    Some thoughts on some work-arounds
    1. Run 2 VMs (then when native calls are required..send a message to the 'native-calling vm' (insure its memory footprint is very low)
    2. Write your exec method via JNI (or does JNI calls also result in a fork of the vm on unix..)
    Test code below (threaded version)
    import java.util.*;
    import java.io.*;
    public class test5 extends Thread
         public void run()
              int loops = 0;
              while (true)
                   loops++;
                   System.out.println("---- iteration " loops "---");
                   makeNativeCall();
         public static void main(String[] args)
              try
                   System.out.println("testing on OS: " + System.getProperty("os.name"));
                   // Allocate a nice chunk of memory
                   byte[] bytes = new byte[1024 * 1000 * 50];
                   test5 tst = new test5();
                   tst.start();
                   while (true)
                        Thread.sleep(1000);
         catch(Exception e)
         {e.printStackTrace();}
    public void makeNativeCall()
              Runtime runtime = Runtime.getRuntime();
    InputStream stderr = null;
    InputStream stdout = null;
              OutputStream stdin = null;
    Process proc = null;
    long totalMem = (long)(runtime.totalMemory()/1024);
    long freeMem = (long)(runtime.freeMemory()/1024);
    long usedMem = (long)((totalMem - freeMem));
    System.out.println("VM REPORT: TOTAL(" totalMem") FREE("+freeMem+") USED(" usedMem")" );
    try
    proc = runtime.exec("sleep 1");
    stderr = proc.getInputStream();
    stdout = proc.getErrorStream();
    stdin = proc.getOutputStream();
    String line = null;
    int i = 0;
    String error = "";
    int exitVal = proc.waitFor();
    if (exitVal != 0)
    System.out.println("ERROR " +exitVal);
    System.out.println("DETIAL" +error);
    catch(Exception e)
    e.printStackTrace();
    finally
    if (stderr != null)
    try{stderr.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdout != null)
    try{stdout.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdin != null)
    try{stdin.close();}catch(Exception ignore){ignore.printStackTrace();}
    if (proc != null)
    try{proc.destroy();}catch(Exception ignore){ignore.printStackTrace();}

  • Can't redirect the Runtime exec output

    I'm trying to get mysqldump to give me some output which I can redirect to the tmp1 location
                   String tmp2 = "mysqldump";
                   Runtime rt1 = Runtime.getRuntime();
                   if(File.separatorChar == '\\') {
                        tmp2 = "\"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump\"";
                   tmp1 = tmp2 + " > " + tmp1;
                   rt1.exec(tmp1);All I want to see at this point is just the error message telling me how to use mysqldump.
    After that I'll do something useful.
    I'm running under NetBeans and if I don't try to redirect I get nothing in the output window.
    Of course, if I run it from a Command box, I see the expected output.
    I know I'm running the program because if I change it to the nonsense mysqldump3, it will tell me that it can't find the file.
    I can't figure out where the output is going and how to capture it.
    Any ideas would be appreciated.
    Ilan

    Ilan wrote:
    Hi Sabre,
    Since I didn't understand your code, I'll use it as a chance to learn something.
    I don't understand what cmd.exe is doing. It is just opening a DOS box?No! It is interpreting the command string.
    Why do you need that? (Maybe I do and I don't know so....)You need to learn a good bit more about your operating system. Get a good book on Windows.
    >
    The simplest thing would be String command = "mysqldump > file.sql".
    Why shouldn't that work?1) Because the directory containing your mysqldump is not in the PATH.
    2) Because the redirection operator '>' is only applicable when interpreted by the command processor (cmd.exe). Reads your Windows manual.
    >
    The reason I need the explicit path is because mysqldump isn't on my Windows path (Linux is nicer that it is in usr/bin, so there is no problem.)
    So I detect Windows and for Windows put the path and command in quotes.
    (Now that I think about it, cmd.exe probably wouldn't work in Linux anyway.)On Linux you will need your shell to interpret the redirection operator '>' .
    >
    What is that "/C" all about? Go to drive c:?
    Your first attempt looks like a confusion with mysqldump, once without a path followed by a path.
    That one I don't understand at all.
    How do I go about getting control of the stderr, if I don't already have control?
    BTW, I haven't yet tried it in Linux. First I'll get the Windows version going.
    Thanks for your reply. I'll try to learn from it.You need to read, read again, study and then implement the recommendations in http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .
    Sorry if this sounds like I'm passing the buck but your lack of knowledge of Windows, Linux and Runtime.exec() means I cannot help without writing a large tutorial.

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

  • Parameter  to shell script using Runtime.exec(string)

    Hi all, ( Speciall hi to dheeraj tak )
    Briefly : How do i pass an arguement to a non - java executible being called using Runtime.exec.
    In detail : i am using Runtime.exec to call a shell script : The code is as follows:
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh"};
    try {
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    This works properly & calls the shell script which in turn invokes some other executible (c file).
    $HOME/midi/test/build/bin/<C-EXECUTIBLE>
    Here i am specifying the name (say hello.exe ) . So far so good.
    I want to make this happen dynamiclaly. so i need to pass the name of the executible as a parameter to the script.
    To pass a parameter i hav to change the string to :-
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh <C-EXECUTIBLE HERE>"};
    and the script to
    $HOME/midi/test/build/bin/$1 --- where $1 refers to argument 1. (C-EXECUTIBLE AGAIN).
    This is giving an IO - Execption. Plz help
    Code will be very helpful.
    Thanx in advance

    some 1 plz tell me the difference :-
    This is the documentation of Runtime.exec that i found :-
    1> exec
    public Process exec(String command) throws IOException
    Executes the specified string command in a separate process.
    The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).
    Parameters:
    command - a specified system command
    Complete refernce says : Process (String progName) ----- Executes a program specified by programname as a seperate process.
    2> exec
    public Process exec(String cmdarray[]) throws IOException
    Executes the specified command and arguments in a separate process.
    The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).
    Parameters:
    cmdarray - array containing the command to call and its arguments.
    Complete reference says : Process exec(String comLineArray[]) ---- Executes the command line specified bythe string in comLineArray as a seperate process.
    This means that there is provision 4 command line arguments...
    how do u use it then????????????????????????????

  • How to run db2 command by using Runtime exec

    Hello
    I am using java. When i am runing db2 command by using Runtime.exec( String cmd, String[] env ). I gave the environment path
    DB2CLP=6259901
    DB2DRIVER=D:\ibm\db2\java\db2java.zip
    DB2HOME=D:\ibm\db2
    DB2INSTANCE=DB2
    DB2MMTOP=D:\CMBISS
    but still I am getting error message
    "DB21061E Command line environment not initialized"
    after setting the above path in the cmd It is working fine. When i am trying thro java programm i am getting the above error. Can I get answer for this.
    bhaski.

    Before you can execute DB2 commands you have to open a DB2 CLP. The following code will do so:
    import java.io.IOException;
    public class Db2 {
         public static void main(String args[]) {
              try {
                   Runtime rt = Runtime.getRuntime();
                   Process child = rt.exec("db2cmd");
                   child.waitFor();
              catch (IOException io) {
                   io.printStackTrace();
              catch (InterruptedException e) {
                   e.printStackTrace();

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

  • Strange behavior when using Runtime.exec() to run batch file

    I've been struggling with this for hours.
    I have a Swing application which upon clicking a button, I want to execute a batch file. This batch file itself uses a command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c start c:\\renew\\renew2\\bin\\win\\renew.bat");
    The program (Renew) will start up no problem, but when I exit Renew, the command window stays put. I want the command window to close. Running Renew stand-alone, upon closing Renew, it will exit the command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c c:\\renew\\renew2\\bin\\win\\renew.bat");
    or
    Runtime load = Runtime.getRuntime();
    load.exec("c:\\renew\\renew2\\bin\\win\\renew.bat");
    When I press the button, sometimes the Renew application will come up right away, sometimes the Renew application will come up after a very long delay, and most times, the Renew application will only come up after I have closed the Swing frame where the button is located. When I use this code, the command window that Renew uses is never visible.
    What I want is to simply have the Renew application behave the same exact way launching from my Swing application as when Renew is being run standalone.
    Any suggestions? Thanks so much.
    Sincerely,
    Will

    Getting rid of start makes the startup time very variable. Sometimes it starts up right away, sometimes after many minutes, most times only after I close my application.
    Thanks, Any other suggestions?
    (BTW, I have read the famous "When Runtime.exec() won't" article, and have tried its suggestions to no avail)
    Message was edited by:
    willies777

  • Where to put files in using runtime.exec(run.exe)?

    I try to use the following program in EJB to call my EXE program in the J2EE server:
    runtime.exec("c:\\j2ee\\public\\exe\\run.exe temp.txt");
    In the execution of mill_turn.exe, it will open several files for read and write.
    So where to put the file temp.txt and other files the run.exe need to read?
    Looks like the J2EE server can not find them?
    Thanks!

    I got it in Java SE1.4.
    File dir=new File("c:\\j2ee\\public_html\\Mill_turn\\exe\\");
    Process proc = rt.exec(cmd,null,dir);Use above codes, I really got the right output from my external program for the first time. But , after that, the output keeps same when I change the filename in the following code:
    cmd="c:\\..\\run.exe temp.prt"
    to
    cmd="c:\\..\\run.exe Abc1.prt" , which must have different output.
    The codes for calling external program are implemented in the SessionBean of J2EE.

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

Maybe you are looking for