java中只有输出流才需要刷新缓冲区
PrintWriter和BufferedWriter都是继承java.io.Writer,所以很多功能都一样。不过PrintWriter提供println()方法可以写不同平台的换行符,而BufferedWriter可以任意设定缓冲大小。
OutputStream可以直接传给PrintWriter(BufferedWriter不能接收),如:
PrintWriter out
= new PrintWriter(new BufferedOutputStream(new FileOutputStream("foo.out")));
或者用OutputStreamWriter来将OutputStream转化为Wrtier.这时就可以用BufferedWriter了。
API documents中都写的很清楚了。
// 执行bash
public static void execCommandByRuntime(String cmd)
{
BufferedInputStream ebis = null;
BufferedInputStream bis = null;
try {
int bufSize = 4096;
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
byte[] buf = new byte[bufSize];
int len;
ebis = new BufferedInputStream(p.getErrorStream(), bufSize);
while ((len = ebis.read(buf)) != -1) {
System.out.println("ERROR CMD:"+cmd);
System.out.write(buf, 0, len);
}
bis = new BufferedInputStream(p.getInputStream(), bufSize);
while ((len = bis.read(buf)) != -1) {
System.out.println("CMD:"+cmd);
System.out.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != ebis) {
ebis.close();
}
if (null != ebis) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
PrintWriter和BufferedWriter都是继承java.io.Writer,所以很多功能都一样。不过PrintWriter提供println()方法可以写不同平台的换行符,而BufferedWriter可以任意设定缓冲大小。
OutputStream可以直接传给PrintWriter(BufferedWriter不能接收),如:
PrintWriter out
= new PrintWriter(new BufferedOutputStream(new FileOutputStream("foo.out")));
或者用OutputStreamWriter来将OutputStream转化为Wrtier.这时就可以用BufferedWriter了。
API documents中都写的很清楚了。
// 执行bash
public static void execCommandByRuntime(String cmd)
{
BufferedInputStream ebis = null;
BufferedInputStream bis = null;
try {
int bufSize = 4096;
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
byte[] buf = new byte[bufSize];
int len;
ebis = new BufferedInputStream(p.getErrorStream(), bufSize);
while ((len = ebis.read(buf)) != -1) {
System.out.println("ERROR CMD:"+cmd);
System.out.write(buf, 0, len);
}
bis = new BufferedInputStream(p.getInputStream(), bufSize);
while ((len = bis.read(buf)) != -1) {
System.out.println("CMD:"+cmd);
System.out.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != ebis) {
ebis.close();
}
if (null != ebis) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}