Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file in java using fileinputstream

I am new to programming, I need help in understanding the difference between 2 ways of creating a fileinputstream object for reading files. I have seen examples on internet, some have used first one and others second one. I am confused which is better and why?

FileInputStream file = new FileInputStream(new File(path));

FileInputStream file = new FileInputStream(path);
like image 814
skumar Avatar asked Aug 11 '26 03:08

skumar


2 Answers

Both are fine. The second one calls the first implicitly.

public FileInputStream(String name) throws FileNotFoundException {
    this(name != null ? new File(name) : null);
}

If you have a reference to the file which should be read, use the former. Else, you should probably use the latter (if you only have the path).

like image 83
TheLostMind Avatar answered Aug 14 '26 16:08

TheLostMind


Don't use either in 2015. Use Files.newInputStream() instead. In a try-with-resources statement, at that:

final Path path = Paths.get("path/to/file");

try (
    final InputStream in = Files.newInputStream(path);
) {
    // do stuff with "in"
}

More generally, don't use anything File in new code in 2015 if you can avoid it. JSR 203, aka NIO2, aka java.nio.file, is incomparably better than java.io.File. And it has been there since 2011.

like image 38
fge Avatar answered Aug 14 '26 18:08

fge