简体   繁体   English

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

[英]new line is missing while writing file using NIO

i am trying to copy the content of one file to new file and somehow new line are missing in the new file and its created as one row, i guess its related to buffer position. 我试图将一个文件的内容复制到新文件,并且在新文件中缺少新行,并且将其创建为一行,我想它与缓冲区位置有关。 following the code that i am using.. 按照我正在使用的代码。

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

        }

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

The line where you're writing the bytes: 您在其中写入字节的行:

buf.put(line.getBytes());

...doesn't include the new line character, you're just writing the bytes of each individual line. ...不包括换行符,您只是在写每行的字节。 You need to write the new line character separately after each instance. 您需要在每个实例之后分别编写换行符。

You might prefer to use Java 7's Files.copy: 您可能更喜欢使用Java 7的Files.copy:

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

One should once write a file copy oneself. 一个人应该自己写一份文件。 However your current version uses the default platform encoding to read the file as text . 但是,当前版本使用默认平台编码将文件读取为文本 This goes wrong on UTF-8 (some illegal multibyte sequences), on the \ nul char, converts the line endings to the default platform ones. 这在UTF-8(某些非法的多字节序列)上是错误的,在\ nul char上会将行尾转换为默认平台行尾。

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" )));

您可以直接使用由System.getProperty("line.separator")插入的System.lineSeparator() System.getProperty("line.separator")

buff.put(System.lineSeparator().toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM