【java】关于out和err混合输出顺序问题

在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");
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值