Reputation: 12484
I came across the following Java code snippet ( source ), that is used to read the last line in a file. It uses two Apache libraries - ReversedLinesFileReader and FileUtils. Here it is :
ReversedLinesFileReader reader = new ReversedLinesFileReader(FileUtils.getFile(file));
String s = "";
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
What I don't understand however, is why do we not simply put in a file path for the argument to ReversedLinesFileReader , and instead we use the FileUtils class.
Why Can't I simply say instead:
File someFile = new File("someFile.txt");
ReversedLinesFileReader reader = new ReversedLinesFileReader( someFile ) ;
thanks
Upvotes: 0
Views: 420
Reputation: 718826
... what is the advantage of using the Apache FileUtils class?
If file
is just one string, there is no advantage. The call to getFile
is going to call new File(file)
... after messing around to cope with the "var-args-ness" of the file
parameter. So in fact, there is a performance penalty for using getFile
in this case, for zero concrete1 benefit.
If file
is a String[]
, then FileUtils.getFile(file)
turns the strings into a file path.
Why Can't I simply say instead ...
Assuming that file
is a String
, you can, and (IMO) you should do what you proposed.
1 - I have seen people argue in cases like this that it is an advantage to avoid using the java.io
classes directly, but frankly I don't buy it.
Upvotes: 3
Reputation: 7867
Using File is fine. ReversedLinesFileReader has a constructor that accepts a File as an input.
The reason you would use FileUtils is if you could benefit from what the FileUtils.getFile() overloaded methods offer, like passing a String[] of path elements, etc.
Other than that, no difference.
Upvotes: 1