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(); }
java cmd
chama
source share