`
wangse
  • 浏览: 30189 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

java读写文件

    博客分类:
  • java
阅读更多
package velcro.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 对文本文件进行读写操作
 */
public class WriteAndReadText {
	/**
	 * 文本文件所在的目录
	 */
	private String textPath;
	/**
	 * 读取文本内容
	 * @param textname 文本名称
	 * @return
	 */
	public String readText(String textname){
		File file=new File(textPath+File.separator+textname);
		try {
			BufferedReader br = new BufferedReader(new java.io.FileReader(file));
			StringBuffer sb = new StringBuffer();
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			br.close();
			return sb.toString();
		} catch (IOException e) {
			LogInfo.error(this.getClass().getName(),e.getLocalizedMessage(),e);
			e.printStackTrace();
			return null;
		}
	}
	}
	/**
	 * 将内容写到文本中
	 * @param textname 文本名称
	 * @param date 写入的内容
	 * @return
	 */
	public boolean writeText(String textname,String date){
		boolean flag=false;
		File filePath=new File(textPath);
		if(!filePath.exists()){
			filePath.mkdirs();
		}
		try {
			FileWriter fw =new FileWriter(textPath+File.separator+textname);
			fw.write(date);
			flag=true;
			if(fw!=null)
				fw.close();
		} catch (IOException e) {
			LogInfo.error(this.getClass().getName(),e.getMessage(),e);
			e.printStackTrace();
		}

		return flag;		
	}
	/**
	 * 在文档后附加内容
	 * @param textName
	 * @param date
	 * @return
	 */
	public boolean appendText(String textName,String date){
		boolean flag=false;
		File filePath=new File(textPath);
		if(!filePath.exists()){
			filePath.mkdirs();
		}
		try {
			FileWriter fw =new FileWriter(textPath+File.separator+textName,true);
			fw.append(date);
			flag=true;
			if(fw!=null)
				fw.close();
		} catch (IOException e) {
			LogInfo.error(this.getClass().getName(),e.fillInStackTrace().toString());
			e.printStackTrace();
		}
		return flag;	
	}
	public String getTextPath() {
		return textPath;
	}
	public void setTextPath(String textPath) {
		this.textPath = textPath;
	}
}



PrintWriter out = new PrintWriter(new FileWriter(logFileName, true), true);
Java读写文件最常用的类是FileInputStream/FileOutputStream和FileReader/FileWriter。
其中FileInputStream和FileOutputStream是基于字节流的,常用于读写二进制文件。
读写字符文件建议使用基于字符的FileReader和FileWriter,省去了字节与字符之间的转换。
但这两个类的构造函数默认使用系统的编码方式,如果文件内容与系统编码方式不一致,可能会出现乱码。
在这种情况下,建议使用FileReader和FileWriter的父类:InputStreamReader/OutputStreamWriter,
它们也是基于字符的,但在构造函数中可以指定编码类型:InputStreamReader(InputStream in, Charset cs) 和OutputStreamWriter(OutputStream out, Charset cs)。

// 读写文件的编码:
InputStreamReader r = new InputStreamReader(new FileInputStream(fileName), “utf-8″);
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),”utf-8″);

分享到:
评论
1 楼 Will.Du 2012-06-07  
思路很清晰,用用看~~

相关推荐

Global site tag (gtag.js) - Google Analytics