Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IO: What's the benefit of using a File-object when reading or writing files?

Tags:

java

I've been showed to read file using the following pattern:

File path = new File("src/modul/lorem.txt");
FileReader fr = new FileReader(path);    
// ... BufferedReader br = new BufferedReader(fr); ... and so on ...

As far as I know file is a class which represents more a path to class then an actual file: Java Docs Now, when I tried using just a String instead of the File-object ...

 // ...
 FileReader fr = new FileReader("src/modul/lorem.txt");
 // ...

... it worked fine too.

Therefore my question:

What's the purpose of making and using a File-object?

Is there a real benefit? Or is it just a pattern one has seen somewhere and then copied without asking?

like image 930
cluster1 Avatar asked Oct 26 '25 23:10

cluster1


1 Answers

This simply depends on your context/requirements.

Java's File class is nothing but an abstraction. It allows you to treat "some thing" knowing that it represents a file system object. Quoting the javadoc:

An abstract representation of file and directory pathnames.

So, in general: if you only need to pass a file name when opening a reader, then a flat string does fine. But as soon as it might be helpful to do other things with that file, then using the abstraction is the way to go.

In other words: keep in mind that a string is just a sequence of characters. It doesn't bear any meaning beyond that. There is no "meta data" there. But as Java is a strictly typed language, we simply have distinct types for things that "mean more" than just "a sequence of characters".

Example: the file class provides methods to check if the file really exists. When using flat strings, you have to wait for the reader to throw an exception at you.

like image 154
GhostCat Avatar answered Oct 29 '25 14:10

GhostCat



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!