日期:2014-05-19  浏览次数:20713 次

如何用io写文件追加内容?

public static void setInfoByProperty(String id,String property,String propertyValue) throws Exception{
File file  = getFile(id);
PrintWriter pw = new PrintWriter(file);
Properties ps = new Properties();
ps.setProperty(property,propertyValue);
ps.list(pw);
pw.flush();
pw.close();
}

如上面方法代码,是根据id找到文件,再把输入相对属性的值写到文件中,但我这样写,每次录入文件都话刷新了上次录入的,怎么才能把新输入的追加到文件中,而不覆盖旧的内容?
------最佳解决方案--------------------


Properties pro = new Properties();
            pro.load(new FileInputStream("readxmllasttime.porperties"));
            for (Enumeration e = pro.propertyNames(); e.hasMoreElements();) {
                String s = (String) e.nextElement(); // 遍历所有元素
                if (s.equals(key)) {
                    /**如果键相同则覆盖*/
                    pro.setProperty(key, maxdate.getTime() + "");
                } else {
/**否则就原样写入*/
                    pro.setProperty(s, pro.getProperty(s));
                }
            }
            pro.store(new FileOutputStream("readxmllasttime.porperties"),"描述信息");

------其他解决方案--------------------
JAVA操作属性文件有很多方法,举个简单例子:
  
File file  = getFile(id);        
 FileInputStream fis = new FileInputStream(file);         
Properties ps = new Properties();
ps.load(fis);         
ps.setProperty(property,propertyValue); 
FileOutputStream fos = new FileOutputStream(file);        
ps.store(fos, "");               
 os.close();
 
------其他解决方案--------------------
先读进来,再写回去。


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

/**
 * 属性文件读写工具
 * @author shanl
 *
 */
public class ResourceUtil {
private File configFile = null;
private Properties prop = null;

public ResourceUtil(URL url){
load(url);
}

/**
 * 从