Java:BufferedWriter跳过换行符 [英] Java: BufferedWriter skipping newline

查看:147
本文介绍了Java:BufferedWriter跳过换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下函数将字符串写入File。该字符串使用换行符进行格式化。

I am using the following function to write a string to a File. The string is formatted with newline characters.

例如, text =sometext \ nsomemoretext \ nlastword;

我可以看到输出文件的换行符:

I am able to see the newline characters of the output file when I do:

type outputfile.txt

然而,当我在记事本中打开文本时,我可以看不到换行符。一切都显示在一行。

However, when I open the text in notepad I can't see the newlines. Everything shows up in a single line.

为什么会发生这种情况。如何确保我正确地写文本以便能够在记事本中正确地看到(格式化)。

Why does this happen. How can I make sure that I write the text properly to be able to see correctly (formatted) in notepad.

    private static void FlushText(String text, File file)
    {
        Writer writer = null;
        try
        {          
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(text);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
        finally
        {
            try
            {
                if (writer != null)
                {
                    writer.close();
                }
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }


推荐答案

在Windows上,按照惯例,新行表示为回车符后跟换行符(CR + LF),即 \\\\ n

On windows, new-lines are represented, by convention, as a carriage-return followed by a line-feed (CR + LF), i.e. \r\n.

来自 Newline维基百科页面


文本编辑器通常用于
转换
不同换行格式之间的文本文件;最现代的
编辑器可以使用
至少使用不同的ASCII CR / LF
约定来读写文件。 标准的Windows
编辑器记事本不是其中之一

(虽然是Wordpad)。

Text editors are often used for converting a text file between different newline formats; most modern editors can read and write files using at least the different ASCII CR/LF conventions. The standard Windows editor Notepad is not one of them (although Wordpad is).

如果将字符串更改为以下内容,记事本应正确显示输出:

Notepad should display the output correctly if you change the string to:

text = "sometext\r\nsomemoretext\r\nlastword";

如果您想要一种独立于平台的方式来表示换行,请使用 System.getProperty(line.separator); 对于 BufferedWriter 的特定情况,请使用bemace建议的内容。

If you want a platform-independent way of representing a new-line, use System.getProperty("line.separator"); For the specific case of a BufferedWriter, go with what bemace suggests.

这篇关于Java:BufferedWriter跳过换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆