Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FileReader vs File

Tags:

java

I wanted to create a File/FileReader object to instantiate a Scanner object.

So, the text book had like this:

File file = new File("filename.txt");

However, our instructor was like, that is wrong, the correct way is:

FileReader file = new FileReader("filename.txt");

Both of them work. So, what's the difference between the two and which one's correct.

like image 952
Boyyett Avatar asked Sep 03 '25 08:09

Boyyett


1 Answers

File(String name)

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

FileWriter(String name)

Constructs a FileWriter object given a file name.

Basically, the difference is that only Instantiating a File won't allow you to write to it, while FileWriter does.

The constructor of FileWriter pass to OutputStreamWriter a new FileOutputStream which instantiate a File from the given name.

Note that a Scanner is used to read a File not to write in it.


Edit : To answer to your edited question where you changed FileWriter to FileReader, the main difference between a File and a FileReader is that File does not have a close method while a FileReader does and implement Closeable. Most of the methods offered by File object are meant to manipulate directly the file (check existence, delete, create, list all files from directory). As @Pshemo mentionned, a File is not to be seen as data, but simply as a path.

I recommend to read the File API and FileReader API.

like image 146
Jean-François Savard Avatar answered Sep 05 '25 00:09

Jean-François Savard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!