2013-03-09 49 views
3

我試圖編寫一個返回文件輸入流的函數。它看起來是這樣的:如何優雅地處理java中的FileNotFoundexception

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

因此,這裏是我的問題 - 顯然不會在出現異常的情況下創建的文件。但我需要一個文件對象來實例化FileInputStream。我有點迷失在這裏,我如何處理異常,同時仍然返回一個有效的FileInputStream對象?

+0

凡是受到特殊行爲影響的東西都應該包裹在「try ... catch」塊中。這會緩解你的問題。 – Makoto 2013-03-09 21:17:10

+1

'new File(「somepath」)'永遠不會拋出異常(儘管它可能會在理論上拋出一個錯誤)。你爲什麼要嘗試它? – cheeken 2013-03-09 21:17:42

+0

@cheeken是正確的 - 唯一可能來自創建文件的異常是NullPointerException,並且通過將靜態字符串作爲構造函數來緩解。 – Makoto 2013-03-09 21:18:56

回答

10

這是進一步拋出異常的想法。只需將該例外拋給調用者。

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

這樣,調用者必須處理它。這是使用它的最乾淨的方式。

備註:您應該知道,實例化一個File對象永遠不會拋出異常。它可能會拋出異常的FileInputStream的實例化。

+3

我會拋出FileNotFoundException,因爲沒有必要擴大類型。 – 2013-03-09 21:24:50

+0

我剛剛學到了一些東西。非常感謝! – Kai 2013-03-10 00:17:16

4

使用File.exists(),它檢查wheater你可以做一些文件。

UPDJava FileOutputStream Create File if not exists):

File yourFile = new File("score.txt"); 
if(!yourFile.exists()) { 
    yourFile.createNewFile(); 
} 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 
+1

@Makoto不,那是錯誤的。 – 2013-03-09 21:19:29

+0

@Makoto:事實並非如此。當你打開一個outputstream到*或者*調用'File.createNewFile()'時,文件被創建。 – 2013-03-09 21:19:48

+0

http://stackoverflow.com/questions/9620683/java-fileoutputstream-create-file-if-not-exists – Mikhail 2013-03-09 21:23:20

0

這裏是我使用的代碼。你可能會覺得它很有趣。

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; 
} 
相關問題