Problem with cmd command output in java

I am trying to read the results of cmd command (e.g. dir). After creating the process, I use BufferedReader in combination with InputStreamReader . For some reason, the BufferedReader continues to be empty, although I know there must be some output that needs to be read.

Here is the code I'm using:

 String[] str = new String[] {"cmd.exe", "/c", "cd", "c:\\", "dir", "/b", "/s" }; Runtime rt = Runtime.getRuntime(); try{ Process p = rt.exec(str); InputStream is =p.getInputStream(); System.out.println(is.available()); InputStreamReader in = new InputStreamReader(is); StringBuffer sb = new StringBuffer(); BufferedReader buff = new BufferedReader(in); String line = buff.readLine(); System.out.println(line); while( line != null ) { sb.append(line + "\n"); System.out.println(line); line = buff.readLine(); } System.out.println( sb ); if ( sb.length() != 0 ){ File f = new File("test.txt"); FileOutputStream fos = new FileOutputStream(f); fos.write(sb.toString().getBytes()); fos.close(); } }catch( Exception ex ) { ex.printStackTrace(); } 
+7
java cmd
source share
3 answers

You have:

 String[] str = new String[] {"cmd.exe", "/c", "cd", "c:\\", "dir", "/b", "/s" }; 

which does not seem right to me. You cannot put multiple commands in cmd.exe on the same command line. This is a batch file.

Try to get rid of everything, both the CD and the directory.

edit: valid:

 C:\>cmd.exe /c cd c:\ dir The system cannot find the path specified. 
+5
source share

There may be a mistake. In this case, you should also capture getErrorStream ()

+1
source share

You execute cmd.exe /c cd c:\ dir /b /s . I donโ€™t think I am doing what you expect.


I mean, you combined the two commands on the same line, and the Windows shell probably doesn't like it. Try something like

 String[] str = new String[] {"cmd.exe", "/c", "cd", "c:\\", "&&", "dir", "/b", "/s" }; 

&& tells the shell to execute cd c:\ , and then execute dir /b /s if the first command was successful.

+1
source share

All Articles