Home » Java » java – Which has best performance, PrintWriter flushing inside the loop or after the loop-Exceptionshub

java – Which has best performance, PrintWriter flushing inside the loop or after the loop-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Im having a array of PrintWriters, Im reading from a file and saving it into multiple files at the same time with multiple PrintWriters.
Like this,

private void splitMeta(String fileName, PrintWriter[] temp) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    int countKeeper = 0;
    while ((line = reader.readLine()) != null) {
        tmpws[countKeeper].write(line + "\n");
        countKeeper = (++countKeeper) % limit;
    }
    reader.close();
    for (PrintWriter printWriter : temp)
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
}

//I am reading a file with more than 1000 's of line.  

is this the best solution or will it be better if i place the flush after the write statement?

How to&Answers: