循环中的缓冲写入器在txt文件中创建空行

时间:2015-03-11 09:53:33

标签: java bufferedwriter

链接到整个代码:http://pastebin.com/Y0FA7zuG

我的代码:

public void dadUpdateFunction(ArrayList<JTextArea> texts)
{
  try{
    //Specify the file name and path here
    File file =new File("C:\\Users\\Karan\\Documents\\dadTXT.txt");

    /* This logic is to create the file if the
     * file is not already present
     */
    if(!file.exists()){
      file.createNewFile();
    }

    //Here true is to append the content to file
    FileWriter fw = new FileWriter(file,true);

    //BufferedWriter writer give better performance
    BufferedWriter bw = new BufferedWriter(fw);
    String content = "Karan";
    int i= 0;

    for(i= 0; i<texts.size(); i++)
    {
      content = (texts.get(i).getText() );
      if(i!=0) 
        bw.newLine();

      if(i>0)   
        texts.get(i-1).setEditable(false);
    }

    bw.write(content + "\n");
    //Closing BufferedWriter Stream
    bw.close();

    System.out.println("Data successfully appended at the end of file");

  }catch(IOException ioe){
     System.out.println("Exception occurred:");
  }
}

所以我有一个JTextArea的arraylist。在我的程序中,用户可以在JTextArea中编写,然后单击此更新按钮,并将最新的JTextArea框中写入的文本添加到txt文件中。但是我在txt文件中输出的输出输出如下:http://pastebin.com/fijFQKZi

我不希望数字之间有空行,因为这会让我的缓冲读卡器变得混乱。为什么要添加这些空行?

我该如何解决这个问题?我是新来的,所以如果我没有正确写东西,请告诉我。 Ť

谢谢!

2 个答案:

答案 0 :(得分:1)

这让我在很多方面感到困惑。在你的循环中,你不断给content一个新值,而不用做任何事情,直到循环结束。同时,除了第一次(该部分有意义)之外,您还要在缓冲区中写入换行符。我认为你需要在循环中移动bw.write(content)并在循环后删除它。

for(i=0; i<texts.size(); i++)
{
    if(i!=0) {
        bw.newLine();
    }
    bw.write(texts.get(i).getText());
    if(i>0) {    
        texts.get(i-1).setEditable(false);
    }
}
bw.close();

答案 1 :(得分:0)

如果您只想要上一个JTextArea内容而不需要额外的newLine,则必须删除

if(i!=0) 
    bw.newLine();

为每个JTextArea添加一个新行。

现在,如果这真的是你想要的,你可以像这样重构:

content = texts.get(texts.size()-1).getText(); // get only the last one
bw.write(content + "\n"); // write last content
for(int i= 0; i<texts.size(); i++)
{
    texts.get(i).setEditable(false);
}
相关问题