Search code examples
javafileconventionsfileinputstreamfileoutputstream

Should a File be created explicitly when creating a stream?


I was wondering about a property of Java's FileInputStreams (and FileOutputStreams as well). When creating them you can use either of these constructors:

public FileInputStream(String name) throws FileNotFoundException

public FileInputStream(File file) throws FileNotFoundException

I often see (and write) code like this:

InputStream in = new FileInputStream(new File("data.txt"));

You can see I create a File there. I could also do it without it:

InputStream in = new FileInputStream("data.txt");

By the JDK source code there seems to be next to no difference between how they work. Here is the source for the constructor that takes String:

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

All of this is basically the same for FileOutputStream.

Is using either one of the constructors a convention I don't know of, and are there any benefits to either? Is it a different case with FileInputStream or FileOutputStream?


Solution

  • Although, the first constructor FileInputStream(String name) is probably used more often, it is only the second one, which is FileInputStream(File file), which allows for accurate checking of the input file using the File class methods before we link it with the InputStream.

    Furthermore, the process of creating an object of FileOutputStream class is not dependent on the existence or possible lack of the appropriate file. When you create an object of FileOutputStream class it will create a file before opening it for future writing. But the attempt to open the read-only file will thrown an exception.