2017-10-17 43 views
1

我做了這個作業練習,從文本文件中讀取文本並將其反轉存儲到另一個新文件中。這是代碼:當使用Java將文件從文件翻轉並存儲到另一個文件時,文件大小減小

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,以便任何掛起的輸出不寫入底層文件。這可能會導致您的文件被截斷。

您應該已經用pw.close()finally中關閉了輸出流,或嘗試使用資源。

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。