向.Txt文件中追加数据
- Java code
List list = new ArrayList(); String[] strread =new String[8]; String str =""; str =gpid+","+gpname+","+gpcomment+","+update+","+operator+","+"0"; String s =""; try { File out = new File("D:/redsun/groupinfo.txt"); File in = new File("D:/redsun/groupinfo.txt"); BufferedWriter output = new BufferedWriter(new FileWriter(out));//在这又把.Txt文件都清空了 output.write(str); output.flush(); output.newLine(); output.close(); BufferedReader input = new BufferedReader(new FileReader(in)); while((s = input.readLine())!=null){ strread =s.split(","); if("0".equals(strread[5])){ list.add(strread[1]); } } input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }
写了以上代码,但执行结果不对,比如我文件里以前有3条数据 但执行完后只剩了追加的这条数据,其余的都覆盖了。
求解决方法
------解决方案--------------------
用这个
FileOutputStream(filename,true);
这里的true表示是在末尾追加。如果为false则在前面追加
不行再找我,我再给你试啊
------解决方案--------------------
FileWriter
public FileWriter(File file,
boolean append)
throws IOException在给出 File 对象的情况下构造一个 FileWriter 对象。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。
参数:
file - 要写入数据的 File 对象
append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
- Java code
BufferedWriter output = new BufferedWriter(new FileWriter(out,true));//
------解决方案--------------------
改成
output.append(str);
------解决方案--------------------
- Java code
BufferedReader input = new BufferedReader(new FileReader(in)); //在这里又清空了
------解决方案--------------------
------解决方案--------------------
没必要开两个内容一样的文件对象
------解决方案--------------------
一楼的解法有点麻烦,我试了试
二楼的是正解
------解决方案--------------------
- Java code
import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.Iterator;public class WriteFile { /** * @param args */ private String gpid="00031"; private String gpname="xmlbook"; private String gpcomment="this is good book for readers"; private String update="2008-03-26"; private String operator = "add + "; public static void main(String[] args) { // TODO Auto-generated method stub List<String> output = new WriteFile().writeEndFile(); Iterator<String> item = output.iterator(); while(item.hasNext()){ System.out.println(item.next()); } } public List<String> writeEndFile(){ ArrayList<String> list = new ArrayList<String>(); String[] strread =new String[8]; String str =""; str =gpid+","+gpname+","+gpcomment+","+update+","+operator+","+"0"; String s =""; try { File out = new File("D:/redsun/groupinfo.txt"); FileOutputStream output = new FileOutputStream(out,true);//在这又把.Txt文件都清空了 output.write(str.getBytes()); output.flush(); output.close(); System.out.println("File writing has done!!"); File in = new File("D:/redsun/groupinfo.txt"); BufferedReader input = new BufferedReader(new FileReader(in)); while((s = input.readLine())!=null){ strread =s.split(","); if("0".equals(strread[strread.length-1])){ list.add(strread[1]); } } input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }}