2009-02-16 52 views
5

如何獲取文本文件的內容,同時保留它是否在文件末尾有換行符?使用這種技術,它是不可能告訴我們,如果文件中的一個新行結束:Java:從文本文件中讀取尾隨的新行

BufferedReader reader = new BufferedReader(new FileReader(fromFile)); 
StringBuilder contents = new StringBuilder(); 

String line = null; 
while ((line=reader.readLine()) != null) { 
    contents.append(line); 
    contents.append("\n"); 
} 
+0

如果您正在使用的BufferedWriter,你也可以使用.newline方法:http://stackoverflow.com/questions/9199216/strings-written-to-file-do-not-preserve-line-breaks – 2016-02-09 11:40:21

回答

0

你可以閱讀使用的技術之一上市here

我最喜歡的整個文件內容是這樣的一個:

public static long copyLarge(InputStream input, OutputStream output) 
     throws IOException { 
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 
    long count = 0; 
    int n = 0; 
    while ((n = input.read(buffer))>=0) { 
     output.write(buffer, 0, n); 
     count += n; 
    } 
    return count; 

}

7

不要使用的readLine();使用read()方法一次傳輸一個字符的內容。如果你在BufferedReader上使用它,這將具有相同的性能,但與上面的代碼不同,它不會「規範化」Windows風格的CR/LF換行符。