5

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?

Perception
  • 79,279
  • 19
  • 185
  • 195
Kai
  • 376
  • 1
  • 4
  • 17
  • Everything that is subject to exceptional behavior should be wrapped in a `try...catch` block. That would mitigate your issue. – Makoto Mar 09 '13 at 21:17
  • 1
    `new File("somepath")` will never throw an exception (though it may throw an error, theoretically). Why are you `try`ing it? – cheeken Mar 09 '13 at 21:17
  • @cheeken is right - the only exception that could come from creating the file would be a NullPointerException, and that's mitigated by having a static string as the constructor. – Makoto Mar 09 '13 at 21:18

3 Answers3

12

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.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
3

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); 
Community
  • 1
  • 1
Mikhail
  • 4,175
  • 15
  • 31
0

Here is the code I use. You might find it interesting.

public static final Charset UTF_8 = Charset.forName("UTF-8");

/**
 * Provide a normalised path name which can contain SimpleDateFormat syntax.
 * <p/>
 * e.g.  'directory/'yyyyMMdd would produce something like "directory/20130225"
 *
 * @param pathName to use. If it starts or ends with a single quote ' treat as a date format and use the current time
 * @return returns the normalise path.
 */
public static String normalisePath(String pathName) {
    if (pathName.startsWith("'") || pathName.endsWith("'"))
        return new SimpleDateFormat(pathName).format(new Date());
    return pathName;
}

/**
 * Convert a path to a Stream. It looks first in local file system and then the class path.
 * This allows you to override local any file int he class path.
 * <p/>
 * If the name starts with an =, treat the string as the contents.  Useful for unit tests
 * <p/>
 * If the name ends with .gz, treat the stream as compressed.
 * <p/>
 * Formats the name with normalisePath(String).
 *
 * @param name of path
 * @return as an InputStream
 * @throws IOException If the file was not found, or the GZIP Stream was corrupt.
 */
public static InputStream asStream(String name) throws IOException {
    String name2 = normalisePath(name);
    // support in memory files for testing purposes
    if (name2.startsWith("="))
        return new ByteArrayInputStream(name2.getBytes(UTF_8));
    InputStream in;
    try {
        in = new FileInputStream(name2);
    } catch (FileNotFoundException e) {
        in = Reflection.getCallerClass(3).getClassLoader().getResourceAsStream(name2);
        if (in == null)
            throw e;
    }
    if (name2.endsWith(".gz") || name2.endsWith(".GZ"))
        in = new GZIPInputStream(in);
    in = new BufferedInputStream(in);
    return in;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130