import java.io.BufferedInputStream;
import java.io.IOException;
public class ExecLs {
static public void main(String[] args) {
String cmd = "ls"
try {
Process ps = Runtime.getRuntime().exec(cmds);
System.out.print(loadStream(ps.getInputStream()));
System.err.print(loadStream(ps.getErrorStream()));
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
// read an input-stream into a String
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while( (ptr = in.read()) != -1 ) {
buffer.append((char)ptr);
}
return buffer.toString();
}
}
import java.io.IOException;
public class ExecLs {
static public void main(String[] args) {
String cmd = "ls"
try {
Process ps = Runtime.getRuntime().exec(cmds);
System.out.print(loadStream(ps.getInputStream()));
System.err.print(loadStream(ps.getErrorStream()));
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
// read an input-stream into a String
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while( (ptr = in.read()) != -1 ) {
buffer.append((char)ptr);
}
return buffer.toString();
}
}
本文介绍了一个简单的Java程序,该程序通过调用Runtime.getRuntime().exec(cmds)来执行系统命令'ls',并读取命令的输出和错误流。程序使用了BufferedInputStream来提高读取效率,并将流内容转换为字符串形式输出。
684

被折叠的 条评论
为什么被折叠?



