我想將一個文件的內容複製到新文件中,並且在新文件中以某種方式刪除了新行,並將其創建爲一行,我猜測它與緩衝區位置有關。 我使用的代碼如下..使用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();
}
}
你永遠不會寫入新行字符! (你的誤解可能是由於'readAllLines'行爲如何:它刪除行分隔符) – assylias
它應該自動添加的問題,或者我需要在閱讀每行後在循環中添加它? –