我正在尝试将一个文件的内容复制到新文件,但不知何故新文件中缺少新行并将其创建为一行,我猜这与缓冲区位置有关。 按照我正在使用的代码..
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();
}
}
最佳答案
在 buf.put(line.getBytes());
之前执行 buff.put(System.getProperty("line.separator").toString());
关于java - 使用 NIO 写入文件时缺少新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16896158/