Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Runtime

How to make this work on windows , the file filename.txt is not being created.

Process p = Runtime.getRuntime().exec("cmd echo name > filename.txt");

Clearly the expected output is a "filename.txt" should be created (C:\Documents and Settings\username\filename.txt ) with the content "name".


Was able to manage with the following code , even though the file was"filename.txt" is not being created with processBuilder

       Runtime runtime = Runtime.getRuntime();
       Process process = runtime.exec("cmd /c cleartool lsview");
       // Directly to file

//Process p = Runtime.getRuntime().exec( 
//              new String[] { "cmd", "/c", "cleartool lsview > filename.txt" },null, new File("C:/Documents and Settings/username/")); 

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

OR , using ProceessBuilder ,

Process process = new ProcessBuilder( "cmd", "/c", "cleartool lsview" ).start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

System.out.printf("Output of running %s is:", Arrays.toString(args));

String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
like image 233
srinannapa Avatar asked Aug 24 '26 04:08

srinannapa


1 Answers

You should actually be using ProcessBuilder instead of Runtime.exec (see the docs).

ProcessBuilder pb = new ProcessBuilder("your_command", "arg1", "arg2");
pb.directory(new File("C:/Documents and Settings/username/"));

OutputStream out = new FileOutputStream("filename.txt");
InputStream in = pb.start().getInputStream();

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
    out.write(buf, 0, len);

out.close();

(I'd adapt it to cmd and echo if I had a windows-machine in reach... Feel free to edit this post!)

like image 80
Nick Avatar answered Aug 25 '26 19:08

Nick