Random printing order for System.out & System.err

2019-01-20 12:06发布

问题:

Please see the code snippet below

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();
                }
            }
        }

    }

}

When I execute the code multiple times , I get output randomly as below , sometimes the System.out statement gets printed first in the console , sometimes the System.err gets printed first. below are the random outputs that I get

Output 1

Finally is executed.File stream is closed.
this is a text file 
and a java program will read this file.

Output 2

this is a text file 
and a java program will read this file.
Finally is executed.File stream is closed.

Why is this so ?

回答1:

I believe this is because you are writing to two different outputs (one is standard out and the other standard error). These are probably handled by two different threads at runtime to allow writing to both during java execution. Assuming this is the case, the cpu task scheduler is not going to execute the threads in the same order every time.

You should never get this functionality if all of your output is going to the same output stream (ie everything goes to standard out or everything goes to standard err). You will never be guaranteed execution order of standard error vs standard output.



回答2:

Because System.out and System.err are both pointing to the console in your case.

To demonstrate, if you add System.out.flush() and System.err.flush() after println(), then the output will be consistant.



回答3:

This has already been answered here:

Java: System.out.println and System.err.println out of order

This happens because your finally clause is using System.out and the other code is using System.err. The err stream is flushing out prior to the out stream or vice versa.

As a result, the order of printed data will not be guaranteed to come out in the same order that it is called.

You can always have your console direct the err stream to a file or the out stream to a file for later inspection. Or, change your code to print everything to System.out. Many programmers do not use err and the usefulness is debatable unless you capture err separate from the console.

Just use out!

Over and out...



标签: java file-io