Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully handle a FileNotFoundexception in java [duplicate]

Tags:

java

exception

I'm trying to write a function which returns a file input stream. It looks something like this:

public FileInputStream getFileInputStream() {
    File file;
    try {
        file = new File("somepath");
    } catch (Exception e) {
    }
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}

So here is my problem - obviously a file isn't created in the case of an exception. But I NEED a file object to instantiate the FileInputStream. I'm kind of lost here, how can I handle the exception while still returning a valid FileInputStream object?

like image 623
Kai Avatar asked Dec 06 '22 08:12

Kai


2 Answers

That is the idea of throwing an exception further. Just throw the exception to the caller.

public FileInputStream getFileInputStream() throws FileNotFoundException
{
    File file = new File("somepath");
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}

This way, the caller has to handle it. This is the cleanest way of working with it.

Remark: You should know that instantiating a File object will never throw an Exception. It is the instantiation of the FileInputStream that might throw an Exception.

like image 79
Martijn Courteaux Avatar answered Dec 21 '22 23:12

Martijn Courteaux


Use File.exists(), it check wheater you can do something with a file.

UPD(Java FileOutputStream Create File if not exists):

File yourFile = new File("score.txt");
if(!yourFile.exists()) {
    yourFile.createNewFile();
} 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 
like image 39
Mikhail Avatar answered Dec 21 '22 23:12

Mikhail