使用 NIO 写入文件时缺少新行

Blu*_*bel 1 java

我正在尝试将一个文件的内容复制到新文件中,但不知何故,新文件中缺少新行并将其创建为一行,我猜它与缓冲区位置有关。按照我正在使用的代码..

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();
            }

        }
Run Code Online (Sandbox Code Playgroud)

Sap*_*Sap 5

buff.put(System.getProperty("line.separator").toString());buf.put(line.getBytes());