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

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

        }

最佳答案

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

关于java - 使用 NIO 写入文件时缺少新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16896158/

相关文章:

java - 在同一 StringBuilder 实例上调用 toString 时的不同输出

java - Apache Shiro - 密码格式问题

java - 使用 drawImage(...) 重复缩放和过滤图像的性能及解决方案

java.sql.SQLException : Column count doesn't match value count at row 1 异常

java - 我的单选按钮代码出了什么问题?

Java/Json - 如何在 HttpPost 请求 header 中添加/传递 ApiKey?

java - 在 Spring 中绑定(bind)期间溢出数字的自定义消息

用于 Web 用户身份验证的 Java 选项

java - 我无法在我的设备上运行该应用程序,错误类型为 3

java - 用于打开 TIFF(类型 4)图像的 Eclipse 扩展?