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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With