2014-11-19 2 views
1

jfv.properties라는 파일을 만들고 있는데이 파일에 간단한 문자열을 쓰려고합니다. 이 파일에서 문자열이 인쇄되지 않습니다. 아래 코드에 문제가 있습니까? 디버그 모드에서 실행 한 예외가 없습니다.파일에 문자열이 인쇄되지 않았습니다.

File file = new File(filePath,"jfv.properties"); 
    FileOutputStream fo = null; 
    try { 
     fo = new FileOutputStream(file); 
     PrintWriter p = new PrintWriter(fo); 
     p.println("some string"); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    }catch (SecurityException s){ 
     s.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    if(fo != null){ 
     try { 
      fo.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

} 
+0

Java 6 또는 Java 7+를 사용하고 있습니까? – fge

+0

게시 된 코드의 원본 버전은 "p.close();" 그러나 나는 그것이 일하는 것을 멈추기 위해 편집되었다는 것을주의한다. – slipperyseal

답변

1

PrintWriter에서 p.close()을 포함하는 경우가 플러시되지 않습니다. 사용

p.println("some string"); 
p.flush(); 

또는 autoFlush

PrintWriter p = new PrintWriter(fo, true); 
p.println("some string"); 

하거나 close를 사용합니다.

autoFlushprintln, printfformat에 사용할 수 있습니다. PrintWriter의 javadoc을 참조하십시오.

세부 사항 PrintWriter 중 하나를 다른 Writer하는 File 또는 파일 이름 또는 OutputStream로 구성 할 수

. javadoc에 OutputStream를 사용하여 인스턴스의 경우는 말한다 :

공공의 PrintWriter (OutputStream에 아웃)

기존의 OutputStream로부터 행의 자동 플래시는 실시하지 않고, 새로운 PrintWriter를 작성합니다. 이 간이 생성자는, 디폴트의 문자 인코딩을 사용해 문자를 바이트로 변환하는, 필요한 중간의 데이터를 생성합니다. OutputStreamWriter

OutputStreamWriter의 자바 독 말한다 :

...가 생성 바이트 기본 출력 스트림에 기록되기 전에, 버퍼에 축적된다. ...

편집

그래서 코드는

fo = new FileOutputStream(file); 
PrintWriter p = new PrintWriter(fo); 

이 스트림 모델로 이어질 것입니다 것은

+-------------+   +--------------------+   +------------------+ 
| PrintWriter | --------> | OutputStreamWriter | -------> | FileOutputStream | 
+-------------+   +--------------------+   +------------------+ 

따라서 println 직접에 문자열을 쓰지 않습니다 FileOutputStream

p.println("some string") 
    +-> outputStreamWriter.write("some string") 
     +--> write to internal buffer (as bytes) 

p.flush(); 
    +-> outputStreamWriter.flush(); 
     +--> internal buffer flush 
     +--> fileOutputStream.write(bytes) 
+0

PrinterWriter가 작업을 수행합니다. 모든 실행에 대해, 우리는 스트림을 닫고 있습니다 (적어도 내가 놓친 것). 왜 우리는 모든 신선한 실행을 위해 그것을 실행하고 싶습니까? –

+0

@JeevanVarughese 귀하의 경우에는 동일한 결과로 연결되는'PrintWriter'를 닫을 수도 있습니다. 그러나'FileWriter'가 아직'FileOutputStream'에 바이트를 쓰지 않았기 때문에'파일에 아무 문자열도 인쇄되지 않았습니다. '라는 의문이 생겼습니다. 아직 플러시되지 않았습니다. 물론'PrintWriter'를 닫아도 플러시됩니다. –

+0

감사합니다 !! 도움이됩니다. Lemme는 빠른 시도를 준다. .. 어떻게 든 그 개념을 놓쳤다! 감사 ! –

1

더 나은 당신이 finally

File file = new File(filePath,"jfv.properties"); 
     FileOutputStream fo = null; 
     try { 
      fo = new FileOutputStream(file); 
      PrintWriter p = new PrintWriter(fo); 
      p.println("some string"); 


     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     }catch (SecurityException s){ 
      s.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
    p.close(); 
if(fo != null){ 
      try { 
       fo.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } 

    } 
+1

이것이 실제 문제였다.나는 파일 스트림을 닫았지만 인쇄 작가를 닫지 않았다. –

1
File file = new File(filePath, "jfv.properties"); 
     FileOutputStream fo = null; 
     BufferedWriter bw = null; 
     FileWriter fw = null; 
     try { 
      fo = new FileOutputStream(file); 
      PrintWriter p = new PrintWriter(fo); 
      p.println("some string"); 
      //change it 
      fw = new FileWriter(file, true); 
      bw = new BufferedWriter(fw); 
      bw.write("some string"); 
      bw.flush(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (SecurityException s) { 
      s.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fo != null) { 
        fo.close(); 
       } 
       if (fw != null) { 
        fw.close(); 
       } 
       if (bw != null) { 
        bw.close(); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
+0

'예외 '를 잡는 것은 나쁜 생각입니다. 검사되지 않은 모든 예외 ('RuntimeException' extends Exception')도 잡아낼 것입니다. – fge

+0

당신이 맞아요, 고마워요. 제발 도와주세요. – sunysen

+0

우리가 한번에 한 번 실을 달릴 때 플러시의 중요성에 대해 확신하지 못했습니다. –

관련 문제