1

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

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

5 回答 5

5

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

于 2013-06-03T12:17:33.003 回答
2

您正在写入字节的行:

buf.put(line.getBytes());

...不包括换行符,你只是在写每一行的字节。您需要在每个实例之后单独编写换行符。

于 2013-06-03T12:00:19.803 回答
1

您可能更喜欢使用 Java 7 的 Files.copy:

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

一个人应该自己写一个文件副本。但是,您当前的版本使用默认平台编码将文件读取为 text。这在 UTF-8(一些非法的多字节序列)上出错,在\u0000nul 字符上,将行尾转换为默认平台行尾。

于 2013-06-03T12:13:57.127 回答
0

This will include the new line:

   ByteBuffer bf = null;
   final String newLine = System.getProperty("line.separator");
   bf = ByteBuffer.wrap((yourString+newLine).getBytes(Charset.forName("UTF-8" )));
于 2014-01-29T16:28:54.470 回答
0

可以直接使用System.lineSeparator()insted ofSystem.getProperty("line.separator")

buff.put(System.lineSeparator().toString());
于 2018-09-18T12:56:07.727 回答