2013-10-21 1 views
1

을 Heres 코드 :이 FileWriter는 어떻게 작동합니까?

java.io.IOException: Stream closed 
    at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source) 
    at sun.nio.cs.StreamEncoder.write(Unknown Source) 
    at sun.nio.cs.StreamEncoder.write(Unknown Source) 
    at java.io.OutputStreamWriter.write(Unknown Source) 
    at FileCharCopier.main(FileCharCopier.java:18) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 

라인 (18) : 나는이 같은 디렉토리에 모두 SCJP 및 scjpcopy.txt이

import java.io.*; 

public class FileCharCopier 
{ 
    public static void main(String args[]) throws IOException 
    { 

    File f1=new File("scjp.txt"); 
    File f2=new File("scjpcopy.txt"); 

    FileReader in=new FileReader(f1); 
    FileWriter out=new FileWriter(f2); 

    int c; 

    while((c=in.read())!=1) 
      { 
     out.write(c); 
     in.close(); 
     out.flush(); 
     out.close(); 


    } 
} 
} 

내가 프로그램을 실행할 때

하지만, 나는 이러한 오류를 얻을 참고

out.write(c); 

누군가가 오류를 수정할 수 있습니까?

+2

당신에게 두 번째 루프 라운드에서 입력 및 출력 스트림을 모두 닫으므로 예외가 발생합니다. – MadProgrammer

+0

초등 오류 이외에 주석에 대한 대답이 나와 있지만 확실히 문자를 복사해서는 안됩니다. 시각. char 배열을 사용해야합니다. 'while ((count = in.read (array))> 0) out.write (array, 0, count);' 그것은 몇 배나 빠릅니다. 그렇지 않으면 BufferedReader와 BufferedWriter. – EJP

답변

0

while 루프에서 라인 in.close()out.close()를 제거하고 이런 식으로합니다

while((c=in.read())!=1) 
{ 
    out.write(c); 
    out.flush(); 
} 

그것은 무엇을 : 파일에서 한 문자를 읽은 후, 그렇게 in이 더 이상 입력 파일로 첨부 된 독자를 닫습니다 예외를 throw합니다.

this 오라클의 문서.
Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

0

는 while 루프 외부에서 out.close();in.close()을 넣어 : 것으로 기록됩니다.

매번 출력 스트림이 닫힙니다. 모든 것을 작성한 후에 while 루프 외부에서 닫을 수 있습니다.

희망 사항.

0

아직 스트림에 쓰려는 동안 스트림을 닫고 있습니다. 정리 프로세스를 루프 밖으로 이동하십시오.

import java.io.*; 
public class FileCharCopier 
{ 
    //...same 
    while((c=in.read())!=1){ 
      out.write(c); 
      out.flush(); 
    } 
      in.close();    
      out.close(); 
    } 
} 
3

기본적으로, 사용자가 입력 및 출력 모두를 닫는 것은 while-loop의 첫 번째 반복에 하네. 즉, 두 번째 시도를 반복하면 스트림이 닫히고 예외가 throw됩니다.

대신 스트림을 완료 한 후에 스트림을 닫아야합니다.

public class FileCharCopier { 

    public static void main(String args[]) throws IOException { 

     File f1 = new File("scjp.txt"); 
     File f2 = new File("scjpcopy.txt"); 

     FileReader in = null; 
     FileWriter out = null; 

     try { 

      in = new FileReader(f1); 
      out = new FileWriter(f2); 

      int c; 

      while ((c = in.read()) != 1) { 
       out.write(c); 
      } 

      out.flush(); 

     } finally { 
      try { 
       out.close(); 
      } catch (Exception e) { 
      } 
      try { 
       in.close(); 
      } catch (Exception e) { 
      } 
     } 
    } 
} 

이 모든 노력은 루프가 존재하거나 일부 오류가 발생하거나하면 스트림을 종료하게되는 것을 보장하기 위해 try-finally 블록을 사용합니다. 당신이 자바 7을 사용하고있을 정도로 운이 좋다면

이제, 당신은

public class FileCharCopier { 

    public static void main(String args[]) throws IOException { 

     File f1 = new File("scjp.txt"); 
     File f2 = new File("scjpcopy.txt"); 

     try (FileReader in = new FileReader(f1); FileWriter out = new FileWriter(f2)) { 

      int c; 

      while ((c = in.read()) != 1) { 
       out.write(c); 
      } 

      out.flush(); 

     } finally { 
     } 
    } 
} 

은 자세한 내용은 The try-with-resources statement에서 봐 ... 예를 들어, 대신 try-with-resources 문을 사용할 수 있습니다