Search code examples
javafileiofilewriterprintwriter

Java - Working with IO - Clarification


I am working on a few lessons in Java, and the instructor started introducing how IO working in Java. I just have a couple of question that an experience Java programmer could clarify.

The piece of code below is a program that creates a (notepad) text file in the same file directory I am writing my code. After that, it simply prints basic lines of text to that file.

import java.io.FileWriter; //Imports Filewriter class
import java.io.PrintWriter; //Imports PrintWriter class
import java.io.IOException; //Imports IOException

public class Chap17Part2
{

    public static void main(String[] args) throws IOException
    {
        String fileName = "grades.txt"; //Creating name for file
        PrintWriter outFile = new PrintWriter(new FileWriter(fileName)); //Question 1
        outFile.println(85); //Prints to file
        outFile.println(77); //Prints to file
        outFile.close(); //Ends buffer, and flushes data to file.

    }

}

Question 1: Due to only brief explanations by the instructor, this line of code is a bit confusing to me. I know that in this line, we are creating the "outFile" object. After that, we are calling the PrintWriter constructor, and inside its parameters, we are calling the constructor for FileWriter. Inside of its constructor, we are calling the name of the file we created as a String. That is the confusing part. I'm not understanding exactly what PrintWriter, and FileWriter are doing. It looks like FileWriter is creating our file, and PrintWriter is giving us the println() method to print the two numbers to the file. After doing research, I have found that you can pretty much achieve the same purpose with both FileWriter, and PrintWriter. What is the purpose for teaching file processing in this manner, and what exactly are the two classes doing? Thank you for the help in clarifying this for me!


Solution

  • The code is equivalent to

    FileWriter fw = new FileWriter(fileName); 
    PrintWriter outFile = new PrintWriter(fw);
    

    So it first creates a FileWriter, which writes characters to a file, and then creates a PrintWriter which prints its values to the FileWriter.