在eclipse执行以下代码时:
public class TestDemo { public static void main(String[] args){ try { Integer.valueOf("abc"); } catch (Exception e) { System.out.println(e); //java.lang.NumberFormatException: For input string: "abc"
System.err.println(e); //java.lang.NumberFormatException: For input string: "abc" } } }
发现输出结果顺序会变动(即err写在后面却可能先被输出),通过网上资料发现原因可能是是:
out往往是带缓存的,而err没有缓存(默认设置,可以改)。所以如果你用标准出错打印出来的东西可以马上显示在屏幕,而标准输出打印出来的东西可能要再积累几个字符才能一起打印出来。如果你在应用中混用标准输出和标准出错就可能看到这个问题。(原文:http://www.jb51.net/article/116612.htm)。
--测试发现使用休眠能一定程度上解决这个问题:
public class TestDemo { public static void main(String[] args){ try { Integer.valueOf("abc"); } catch (Exception e) { System.out.println(e); //System.out.flush(); try { Thread.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } System.err.println(e); } }
补充:通过System.setOut()和setErr()可以重新定向输出位置,例如向文件(D:\hello.txt)输出:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class TestDemo {
public static void main(String[] args) throws IOException{
//true为表示追加,不然新加文字会覆盖之前的内容。
System.setOut(new PrintStream(new FileOutputStream(new File("d:"+File.separator+"hello.txt"),true)));
System.setErr(new PrintStream(new FileOutputStream(new File("d:"+File.separator+"hello.txt"),true)));
System.out.println("1o");
System.out.println("2o");
System.err.println("1e");
System.err.println("2e");
}
}