Search code examples
javafileinputstream

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);

Solution

  • 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).