`
收藏列表
标题 标签 来源
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;
	}
}

Global site tag (gtag.js) - Google Analytics