2013-03-09 5 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

+1

'new File ("somepath")'는 결코 예외를 던지지 않을 것입니다 (이론적으로는 오류가 발생할 수도 있음). 왜 그걸 시험해 보려니? – cheeken

+0

@cheeken이 맞습니다. 파일을 만들 때 올 수있는 유일한 예외는 NullPointerException이 될 수 있으며 정적 문자열을 생성자로 사용하여 완화됩니다. – Makoto

답변

10

예외를 더 던지는 아이디어입니다. 호출자에게 예외를 던지십시오.

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

이렇게하면 호출자가 처리해야합니다. 이것이 가장 깨끗한 작업 방법입니다.

비고 : File 개체를 인스턴스화하면 예외가 발생하지 않습니다. 예외를 throw하는 것은 FileInputStream의 인스턴스입니다.

+3

유형을 확장 할 필요가 없으므로'FileNotFoundException'을 throw합니다. –

+0

방금 ​​배웠습니다. 정말 고맙습니다! – Kai

4

File.exists()을 사용하면 파일로 뭔가를 할 수 있는지 확인합니다.

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

@Makoto 아니, 그게 틀렸어. –

+0

@Makoto : 그건 사실이 아니야. 출력 스트림을 열거 나 * File.createNewFile()을 호출하면 파일이 생성됩니다. –

+0

http://stackoverflow.com/questions/9620683/java-fileoutputstream-create-file-if-not-exists – Mikhail

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; 
} 
관련 문제