Java JTextPane附加空行

Java JTextPane附加空行,java,string,swing,jtextpane,styleddocument,Java,String,Swing,Jtextpane,Styleddocument,我有一个JTextPane,我用以下方法设置它的文本 public void setConfigPaneText(String content, Style style) { StyledDocument logDoc = configPane.getStyledDocument(); if(style == null) { style = configPane.addStyle("Style", null); StyleConstant

我有一个JTextPane,我用以下方法设置它的文本

public void setConfigPaneText(String content, Style style)
{
    StyledDocument logDoc = configPane.getStyledDocument();

    if(style == null)
    {
        style = configPane.addStyle("Style", null);
        StyleConstants.setForeground(style, Color.white);
        StyleConstants.setBold(style, true);
    }

    try 
    {
        configPane.setText(null);
        logDoc.insertString(logDoc.getLength(), content, style);
    }
    catch (BadLocationException e1)
    {
        e1.printStackTrace();
    }
}
我构建的内容字符串如下所示:

            if(f.exists())
            {
                Scanner scan = new Scanner(f);
                while(scan.hasNextLine()) 
                {
                    strbld.append(scan.nextLine()+"\n");
                }                   
                TopologyMain.nodes.get(i).setPtpConfig(strbld.toString()); // output
                scan.close();
            }
因此,我让这个字符串正确地出现在JTextPane中,问题是,当我将JTextPane的内容保存到txt文件并重新加载到JTextPane中时,每行后面都会出现一个新的空行。

图片如下:

代码正在保存

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileChooser.getSelectedFile().getAbsolutePath())));
    out.print(configPane.getText());
    out.close()
并加载:

if(filetmp.exists()) 
{
    Scanner scan;
    try 
    {
        scan = new Scanner(filetmp);

        while(scan.hasNextLine()) 
        {
            strbld.append(scan.nextLine()+"\n");
        }                   

        setConfigPaneText(strbld.toString(), null);

        scan.close();
    } 
    catch (FileNotFoundException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }
如果此方法中没有/n,则如下所示:

问题的原因可能是我在行尾有一个额外的“\r”字符,如图所示:。但我不知道他们从哪里来


谢谢你的时间

这里的问题是您添加了两次“\n”。一次是在构建内容字符串时,一次是在加载文件时。如果删除加载函数中的“\n”,则应看到没有额外空行的文本。

在加载函数中,不应为每个扫描行添加换行符,请尝试以下操作:

while(scan.hasNextLine()) 
{
  strbld.append(scan.nextLine());
} 
意见中的解决方案:


问题的原因是,可以看到我有多个CR(
“\r”
)字符。您可以使用notepad++的show all character函数检查输出的txt文件,自己查找。然后检查与JTextPane或用作内容的字符串相关的所有代码部分,以查找其他CR并删除它们。

我已经尝试过了,很抱歉在问题中没有提及。load方法中没有/n的结果是:如果没有/n,就根本没有换行。然后我假设保存的文本文件的换行符有问题。试着用notepad++的show all character函数检查它。无论如何,可以这样添加换行符:我指的是strbld.append(System.getProperty(“line.separator”);是的,我知道了。这种添加换行符的方法具有相同的结果。但是notepadd++的想法很有用,结果我有一个额外的CR字符。现在的问题是:为什么?。我的加载和保存方法中都没有“\r”。这可能是windows的一项功能。Afaik windows在内部为新行使用\r\n。