写入文件但只保存最后一行 [英] Writing to a file but only last line saved

查看:209
本文介绍了写入文件但只保存最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试复制文本文件,但是当代码完成执行时,我只有文件中的最后一行文本。显然 scanLine()会一直覆盖同一行,但我无法解决这个问题。有什么想法吗?

I am trying to copy a text file but when the code finishes executing I only have the last line of text in the file. Obviously the scanLine() keeps overwriting the same line but I cant figure out to solve this problem. Any ideas?

do{                 
  try{ 
    FileWriter name = new FileWriter("/home/fok/Desktop/out");
    BufferedWriter out = new BufferedWriter(name);
    a=x.nextLine();scanner x grabs next line and sets it string a
    out.write(a);//writes a to file
    out.close();//closees file
  } catch (IOException ioe){
    System.out.println("file writer error");
  } 

} while(x.hasNext());


推荐答案

这很简单,你正在关闭并打开for循环中的文件。

It is pretty simple, you are closing and opening the file inside the for loop.

 public void readfile(){
   try {           
     FileWriter name = new FileWriter("/home/fok/Desktop/out");
     BufferedWriter out = new BufferedWriter(name);
      do {                 
        a=x.nextLine();scanner x grabs next line and sets it string a
        out.write(a);//writes a to file
      } while(x.hasNext());
      out.close();//closees file
   } catch (IOException ioe){
      System.out.println("file writer error");
  }
}

这篇关于写入文件但只保存最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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