2011-03-28 5 views
3

여기 내 코드가 있습니다.자바가 파일을 읽지 않는다면 파일을 읽는다.

public String path; 
public String fileName; 
public static void readData() throws IOException{ 
    try { 
     path="myPath" 
     fileName="myFileName"; 
     fstream = new FileInputStream(path+fileName); 
     br = new BufferedReader(new InputStreamReader(fstream)); 
     //do something...// 
     } 
     br.close(); 
    } catch (FileNotFoundException ex) { 
     JOptionPane.showMessageDialog(null, "Reading file error"); 
     Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

fstream이 있는지 확인하는 방법을 알고 싶었습니다. 존재하지 않으면 새 파일을 작성해야합니다. 어떻게해야합니까? 감사

답변

6

여기에 가능한 솔루션입니다 :

public static void readData() throws IOException 
{ 
    File file = new File(path, filename); 

    if (!file.isFile() && !file.createNewFile()) 
    { 
     throw new IOException("Error creating new file: " + file.getAbsolutePath()); 
    } 

    BufferedReader r = new BufferedReader(new FileReader(file)); 

    try 
    { 
     // read data 
    }finally 
    { 
     r.close(); 
    } 
} 
+0

기본 문자 세트를 사용하는'FileReader' 대신에'Charset'을 지정하는'InputStreamReader'를 사용하여 보길 원할 수도 있습니다 ... – Jesse

+0

Jesse! 내 문제가 해결되었습니다. – Franky

1

파일 filenamepath에 있는지 확인하려면 new File(path, filename).exists()을 사용할 수 있습니다.

exists method은 파일 또는 디렉토리가 지정된 File에 존재하면 true를 반환합니다.

파일이 디렉터리가 아니라 파일인지 확인하려면 isFile method을 사용할 수 있습니다.

자세한 내용은 javadoc for java.io.File을 참조하십시오.

+0

더 나은'new File (path, filename) .exists()'는 현재 운영 체제에 대한 올바른 경로 구분 기호를 자동으로 삽입합니다. – Ceilingfish

+0

좋은 지적 - 나는 나의 대답을 편집했다. 감사! – Greg

-1

당신은 이미 FileNotFoundException을 붙잡고 있습니다. 이것은 당신이 읽고 자하는 파일이 존재하지 않으며 당신이 그것을 창조 할 수 있다는 것을 알고있는 곳입니다.

0
if(new File("filename").exists()) 
    ... 

원하는대로해야합니다.

2

뭔가 코드에서 실종 - 아니 해당 중괄호와 닫는 중괄호가있다. 귀하의 질문에 대답 할 수 있지만

는 먼저 File 개체를 만들고 exists() 다음 createNewFile()exists() 경우 반환 false를 사용합니다. 파일 이름 대신 File 개체를 FileInputStream 생성자에 전달하십시오.

현재로서는 질문에 입력 한 것보다 Google에서 대답하는 시간이 적습니다.

관련 문제