2013-06-03 18 views
0

我想將一個文件的內容複製到新文件中,並且在新文件中以某種方式刪除了新行,並將其創建爲一行,我猜測它與緩衝區位置有關。 我使用的代碼如下..使用NIO寫文件時缺少新行

List<String> lines; 
     FileChannel destination = null; 
     try 
     { 
      lines = Files.readAllLines(Paths.get(sourceFile.getAbsolutePath()), Charset.defaultCharset()); 
      destination = new FileOutputStream(destFile).getChannel(); 
      ByteBuffer buf = ByteBuffer.allocate(1024); 
      for (String line : lines) 
      { 
       System.out.println(line); 
       buf.clear(); 
       buf.put(line.getBytes()); 
       buf.flip(); 
       while (buf.hasRemaining()) 
       { 
        destination.write(buf); 
       } 
      } 
     } 
     finally 
     { 
      if (destination != null) 
      { 
       destination.close(); 
      } 

     } 
+4

你永遠不會寫入新行字符! (你的誤解可能是由於'readAllLines'行爲如何:它刪除行分隔符) – assylias

+0

它應該自動添加的問題,或者我需要在閱讀每行後在循環中添加它? –

回答

4

待辦事項buff.put(System.getProperty("line.separator").toString());buf.put(line.getBytes());

1

,你正在寫字節行:

buf.put(line.getBytes()); 

...不包括新行字符,你只是寫每一行的字節。您需要在每個實例之後單獨編寫新的行字符。

+0

我添加了新的一行到循環內部,它的工作正常,我的問題爲什麼會發生這種情況 –

+0

如果我有一個包含3個不同「行」的列表 - 比如說「行1」,「行2」和「行3」 ,那麼這些行在它們中沒有任何新的行字符。所以如果你把它們寫出來,你需要手動把它們放回去(否則你會得到你觀察到的行爲)。 – berry120

1

你可能更願意使用Java 7的Files.copy:

Files.copy(sourceFile.toPath(), destinationFile.toPath(), 
     StandardCopyOption.REPLACE_EXISTING); 

人們應該一次性編寫一個文件複製自己。 但是,您當前的版本使用默認平臺編碼將文件讀爲文本。這在UTF-8上出錯(一些非法多字節序列),在\u0000 nul字符處,將行結尾轉換爲默認平臺結尾。

0

這將包括新的生產線:

ByteBuffer bf = null; 
    final String newLine = System.getProperty("line.separator"); 
    bf = ByteBuffer.wrap((yourString+newLine).getBytes(Charset.forName("UTF-8")));