Search code examples
javaiofilewriterprintwriterbufferedwriter

writing to a file in Java using printWriter by two ways, which one is better and why?


I have the following methods that creates and writes to that file.

// Create the file and the PrintWriter that will write to the file

    private static PrintWriter createFile(String fileName){

        try{

            // Creates a File object that allows you to work with files on the hardrive

            File listOfNames = new File(fileName);


            PrintWriter infoToWrite = new PrintWriter(new BufferedWriter(
                    new FileWriter(listOfNames);
            return infoToWrite;
        }

        // You have to catch this when you call FileWriter

        catch(IOException e){

            System.out.println("An I/O Error Occurred");

            // Closes the program

            System.exit(0);

        }
        return null;

    }

The program works fine, even if I dont have bufferedWriter and FileWriter like below. how does they two objects help in making the writing process better? I can avoid creating two objects in this case.

PrintWriter infoToWrite = new PrintWriter((listOfNames);

Solution

  • BufferedWriter

    In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

    If you're writing large blocks of text at once (like entire lines) then you probably won't notice a difference. If you have a lot of code that appends a single character at a time, however, a BufferedWriter will be much more efficient.