JAVA中err按顺序输出_System.out和System.err调用的随机打印顺序

本文探讨了在JAVA程序中,System.out和System.err如何可能出现随机打印顺序的问题。示例代码展示了读取文件过程中使用System.err和System.out的情况。在不同执行中,错误输出和正常输出可能会交替出现在控制台上,原因在于它们都写入标准输出,但System.err通常被缓冲,导致打印顺序不确定。
摘要由CSDN通过智能技术生成

请参见下面的代码段

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class ReadFile {

public static void main(String[] args) {

String str="";

FileReader fileReader=null;

try{

// I am running on windows only & hence the path :)

File file=new File("D:\\Users\\jenco\\Desktop\\readme.txt");

fileReader=new FileReader(file);

BufferedReader bufferedReader=new BufferedReader(fileReader);

while((str=bufferedReader.readLine())!=null){

System.err.println(str);

}

}catch(Exception exception){

System.err.println("Error occured while reading the file : " + exception.getMessage());

exception.printStackTrace();

}

finally {

if (fileReader != null) {

try {

fileReader.close();

System.out.println("Finally is executed.File stream is closed.");

} catch (IOException ioException) {

ioException.printStackTrace();

}

}

}

}

}

当我多次执行代码时,我会如下随机获得输出,有时System.out语句首先在控制台中打印,有时System.err首先打印。以下是我得到的随机输出

输出1

Finally is executed.File stream is closed.

this is a text file

and a java program will read this file.

输出2

this is a text file

and a java program will read this file.

Finally is executed.File stream is closed.

为什么会这样呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值