2017-10-17 1 views
1

나는이 숙제를 텍스트 파일의 텍스트를 읽고 다른 새로운 파일로 되돌리기 위해 저장했다. 이 코드입니다 :자바를 사용하여 파일에서 텍스트를 역전하고 저장할 때 크기가 줄어든다

import java.util.*; 
import java.io.*; 

    public class FileEcho { 

File file; 
Scanner scanner; 
String filename = "words.txt"; 
File file1 ; 
      PrintWriter pw ; 
void echo() { 
    try { 
     String line; 

     file = new File(filename); 
     scanner = new Scanner(file); 
     file1 = new File("brabuhr.txt"); 
     pw = new PrintWriter(file1); 


     while (scanner.hasNextLine()) { 
      line = scanner.nextLine(); 
      String s = new StringBuilder(line).reverse().toString(); 

      pw.println(s); 
     } 
     scanner.close(); 
    } catch(FileNotFoundException e) { 
     System.out.println("Could not find or open file <"+filename+">\n"+e 
); 
    } 
} 

public static void main(String[] args) { 
    new FileEcho().echo(); 
} 
} 

여기에 사진이 Picture here

문제는이다 : 새로 생성 된 파일이 동일한 문자를 가지고 있지만 반대에도 불구하고 크기가 감소되는 이유는 무엇입니까?

왜 내 교수조차도 그 이유를 알지 못해 누군가 설명 할 수 있다면 좋을 것입니다.

p.S; 파일의 컨텍스트는 사전의 일부 단어입니다. 또한 다른 학생 컴퓨터에서도 문제가 내 컴퓨터에서 발생하지 않습니다.

+2

왜 그런가요? 즉, 어떤 결과가 그렇게 설명 할 수없는 것입니까? 혹시 Windows에서 이걸 실행하셨습니까? 원본 파일의'\ n \ r'과 작성한'\ n'의 차이를 계산 했습니까? –

+0

그래서'brabuhr.txt'를 쓰고'words.txt'를 읽으십니까? 앞으로의 개발을 위해 변수를 명명하는 것이 좋습니다. 그러면 코드를 빨리 이해하는 것이 더 쉬울 것입니다. – Thomas

+0

@ M.leRutte 파일의 크기가 다릅니다. – Oleg

답변

1

출력 스트림 pw을 절대로 닫지 않아 보류중인 출력이 기본 파일에 기록되지 않는 것이 문제입니다. 이로 인해 파일이 잘릴 수 있습니다.

finallypw.close()으로 출력 스트림을 닫았거나 리소스가있는 try를 닫아야합니다.

try (pw = new PrintWriter(file1)) { 
    while (scanner.hasNextLine()) { 
     line = scanner.nextLine(); 
     String s = new StringBuilder(line).reverse().toString(); 
     pw.println(s); 
    } 
} 

귀하의 구현은 다음으로 단순화 할 수있다 :이 예에서

import java.io.IOException; 
import java.io.PrintWriter; 
import java.nio.file.Files; 
import java.nio.file.Paths; 

public class FileEcho { 
    void echo() throws IOException { 
     try (PrintWriter pw = new PrintWriter("brabuhr.txt")) { 
      Files.lines(Paths.get("words.txt")) 
       .map(s -> new StringBuilder(s).reverse().toString()) 
       .forEach(pw::println); 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     new FileEcho().echo(); 
    } 
} 

내가 사용하는 '시도 -과 - 자원'이 PrintWriter pw이 autoclosed 가지고.

관련 문제