Java System.out&;的随机打印顺序;System.err调用

Java System.out&;的随机打印顺序;System.err调用,java,file-io,Java,File Io,请参阅下面的代码片段 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;

请参阅下面的代码片段

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 产出2
为什么会这样?

我认为这是因为您正在写入两个不同的输出(一个是标准输出,另一个是标准错误)。它们可能在运行时由两个不同的线程处理,以允许在java执行期间写入这两个线程。假设是这样,cpu任务调度器不会每次都以相同的顺序执行线程


如果您的所有输出都指向同一个输出流(即所有输出都指向标准输出或所有输出都指向标准错误),则永远不应该获得此功能。您永远无法保证标准错误与标准输出的执行顺序

这里已经回答了这个问题:

发生这种情况是因为finally子句使用System.out,而另一个代码使用System.err。err流在流出流之前被冲出,反之亦然

因此,无法保证打印数据的顺序与调用的顺序相同

您始终可以让控制台将错误流定向到文件,或将输出流定向到文件,以供以后检查。或者,更改代码以将所有内容打印到System.out。许多程序员不使用err,除非您单独从控制台捕获err,否则其有用性是有争议的

用完就行了


一遍又一遍…

因为在您的案例中,System.out和System.err都指向控制台


为了演示,如果在println()之后添加System.out.flush()和System.err.flush(),那么输出将是一致的。

是因为缓冲的读取器吗?我认为stderr是缓冲的,但我可能是错误的,不需要谈论两个不同的线程。。。关键是标准输出和错误在这里是不同的流:-)
Finally is executed.File stream is closed.
this is a text file 
and a java program will read this file.
this is a text file 
and a java program will read this file.
Finally is executed.File stream is closed.