论坛首页 入门技术论坛

如何在文件后面追加一段内容

浏览 5328 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-07-16  
操作一个文件的时候  如果需要追加  我们的做法一般都是把整个文件先读到一个str里 然后再在str3=str+str2 然后再把str3写回文件里

总感觉这样比较麻烦  而且如果文件过大  肯定会内存溢出  有什么别的办法直接在文件后面追加内容么
   发表时间:2007-07-17  
试试用writer的append方法
0 请登录后投票
   发表时间:2007-07-17  
google "java append file"
0 请登录后投票
   发表时间:2007-07-17  
谢谢ro大大  找到了

引用
public FileOutputStream(String name,
                        boolean append)
                 throws FileNotFoundException

Parameters:
    name - the system-dependent file name
    append - if true, then bytes will be written to the end of the file rather than the beginning
0 请登录后投票
   发表时间:2007-07-18  
package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

public class FileRW {
	public static void main(String[] a)  {
		try {
			FileOutputStream fos = new FileOutputStream (new File("d:\\abc.txt"),true ) ; 
			String str = "ABC \n" ;
			fos.write(str.getBytes()) ;
			fos.close ();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			FileWriter fw = new FileWriter("d:\\abc.txt",true);
			PrintWriter pw=new PrintWriter(fw);
			pw.println("append content");
			pw.close () ;
			fw.close () ;
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		try {
		 RandomAccessFile rf=new RandomAccessFile("d:\\abc.txt","rw"); 
		 rf.seek(rf.length());	//将指针移动到文件末尾 
		 rf.writeBytes("Append a line again!\n"); 
		 rf.close();//关闭文件流 
		}catch (IOException e){
			e.printStackTrace(); 
		}
		
		
	}

}

0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics