簡體   English   中英

使用NIO寫入文件時缺少新行

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

我試圖將一個文件的內容復制到新文件,並且在新文件中缺少新行,並且將其創建為一行,我想它與緩沖區位置有關。 按照我正在使用的代碼。

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

        }

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

您在其中寫入字節的行:

buf.put(line.getBytes());

...不包括換行符,您只是在寫每行的字節。 您需要在每個實例之后分別編寫換行符。

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

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

一個人應該自己寫一份文件。 但是,當前版本使用默認平台編碼將文件讀取為文本 這在UTF-8(某些非法的多字節序列)上是錯誤的,在\ nul char上會將行尾轉換為默認平台行尾。

這將包括新行:

   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