"Hello, Amigo! Yesterday Rishi told you about FileInputStream and FileOutputStream. And today I will tell you about the FileReader and FileWriter classes."
As you probably already guessed, all these classes are adapters between the File object and the InputStream, OutputStream, Reader, and Writer «interfaces».
"They are similar to adapters between File and Reader/Writer, but you only need to pass a String object to the constructor, not a File!"
"Actually, they have several constructors. There are constructors for both File and String objects. If you pass a String object to the constructor, then the constructor will quietly create a File object using the file path taken from the passed String object."
This is for convenience. Java's creators took the most frequent use cases for these classes and wrote constructors for all of them. That's pretty convenient, don't you think?
"Oh, yes. Convenient. I agree. But why then do I have to constantly write:"
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
"Why didn't they add this use case?"
"The issue here is that a typical Java program doesn't work with the console. In truth, you almost never read anything from it. Even with a web server, application server, or some other complicated system."
But we do have PrintStream for outputting data and text to the console. Because these «server applications» often do use the console to display their status, errors, and all sorts of other information.
"Got it. And you can also copy a file using FileReader and FileWriter?"
"Yes, if it's a text file (i.e. it consists of characters). Here's an example:"
public static void main(String[] args) throws Exception
{
FileReader reader = new FileReader("c:/data.txt");
FileWriter writer = new FileWriter("c:/result.txt");
while (reader.ready()) //as long as there are unread bytes in the input stream
{
int data = reader.read(); //Read one character (the char will be widened to an int)
writer.write(data); //Write one character (the int will be truncated/narrowed to a char)
}
//Close the streams after we done using them
reader.close();
writer.close();
}
"Almost no differences."
"Yeah, the differences are minimal."
GO TO FULL VERSION