日期:2014-05-20  浏览次数:20910 次

java 读写txt文件 以及 替换或向txt文件追加内容(play framework)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

import play.Logger;
import play.mvc.Controller;
import util.XString;

/**
	 * <p>生成一个指定长度的随机字符串</p>
	 * <p>长度介于4和256之间</p>
	 * @author rainyhao
	 * @since 2013-7-31 下午3:43:56
	 * @param length 字符串长度 如果长度大于256, 则按256处理, 如果长度小于4, 则按4处理
	 * @return
	 */
	public static final String random(int length) {
		if (length < 4) {
			length = 4;
		} 
		if (length > 256) {
			length = 256;
		}
		char[] buffer = new char[length];
		Random rand = new Random();
		for (int i = 0; i < buffer.length; i++) {
			int randIndex = rand.nextInt(LETTERS.length);
			buffer[i] = LETTERS[randIndex];
		}
		return new String(buffer);
	}
private static final char[] LETTERS = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
											'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
											'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
											'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
											'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};


/**
	 * <p>更新命名实体信息文件</p>
	 * <p>返回</p>
	 * @author Lingdong
	 * @since  2013-12-27 下午12:58:48
	 * @param file
	 */
	public static void updateNameEntity(File file, Integer etype){
		try {
			if(null!=file){
				updateNameEntityFile(file, etype, System.currentTimeMillis());
			}
		} catch (Exception e) {
			Logger.error(e, " Error get updateNameEntity NameEntity.updateNameEntity ");
			renderJSON("error");
		}
		//render("sz.html");
		redirect("Application.testSentiment");
	}
	
	/**
	 * <p>替换命名实体信息文件</p>
	 * <p>返回</p>
	 * @author Lingdong
	 * @since  2013-12-27 下午12:58:53
	 * @param file
	 */
	public static void insteadNameEntity(File file, Integer etype){
		try {
			if(null!=file){
				saveNameEntityFile(file, etype, System.currentTimeMillis());
			}
		} catch (Exception e) {
			Logger.error(e, " Error get insteadNameEntity NameEntity.insteadNameEntity ");
			renderJSON("error");
		}
		//render("sz.html");	
		redirect("Application.testSentiment");
	}


// 保存更新上传的TXT文件 , 向txt追加内容,并返回实际保存在服务器上的文件名
	private static String updateNameEntityFile(File uploaded, Integer etype, Long time) throws IOException {
		String filePath = util.Constants.NAMEENTITY_FILE_PEOPLE_PATH;
		String fn = "people";
		if(etype!=1){
			filePath = util.Constants.NAMEENTITY_FILE_COMPANY_PATH;
			fn = "company";
		}
		// 上传后实际保存在服务器上的文件名: 
		String saveName = fn + "_" + time + "_" + XString.random(8) + uploaded.getName().substring(uploaded.getName().lastIndexOf("."));//"_" + System.currentTimeMillis() + "_" + XString.random(8) + "_" + uploaded.getName();
		// 创建保存目录
		File toSave = new File(filePath + "a/");
		if (!toSave.exists()) {
			toSave.mkdirs();
		}
		// 保存文件
		toSave = new File(filePath + "a/" + saveName);
		File checkFile = new File(filePath + "b/check.txt");
		if(checkFile.exists()){//删除校验文件
			play.libs.Files.delete(checkFile);
		}
		play.libs.Files.copy(uploaded, toSave);//写入添加的文件到A目录
		File bFile = new File(filePath + "b/");
		if (!bFile.exists()) {
			bFile.mkdirs();
		}
		bFile = new File(filePath + "b/" + fn + ".txt");
		String line="";
		//FileReader reader = new FileReader(toSave);
		InputStreamReader isr = new InputStreamReader(new FileInputStream(toSave),"utf-8");
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(bFile,true), "utf-8");
		//FileWriter writer = new FileWriter(bFile,true);
		BufferedReader br = new BufferedReader(isr);//new InputStreamReader(new FileInputStream(toSave),"utf-8");
		BufferedWriter bw = new BufferedWriter(osw);
		while((line=br.readLine())!=null){
			System.out.println(line);
			
		    bw.write(new String(line));
		    bw.newLine();
		}
		bw.flush();
		br.close();
		bw.close();
		isr.close();
		osw.close();
		//reader.close();
		//writer.close();
		
		checkFile.createNewFile();//重新创建校验文件
		return saveName;
	}


// 保存替换上传的TXT文件, 并返回实际保存在服务器上的文件名
	private static String saveNameEntityFile(File uploaded, Integer etype, Long time) throws IOException {
		String filePath = util.Constants.NAMEENTITY_FILE_PEOPLE_PATH;
		String fn = "people";
		if(etype!=1){
			filePath = util.Constants.NAMEENTITY_FILE_COMPANY_PATH;
			fn = "company";
		}
		System.out.println("instead");
		// 上传后实际保存在服务器上的文件名: 
		String saveName = fn + "_" + time + "_" + XString.random(8) + uploaded.getName().substring(uploaded.getName().lastIndexOf("."));//"_" + System.currentTimeMillis() + "_" + XString.random(8) + "_" + uploaded.getName();
		// 创建保存目录
		File toSave = new File(filePath + "a/");
		if (!toSave.exists()) {
			toSave.mkdirs();
		}
		// 保存文件
		toSave = new File(filePath + "a/" + saveName);
		File checkFile = new File(filePath + "b/check.txt");
		if(checkFile.exists()){//删除B目录校验文件
			play.libs.Files.delete(checkFile);
		}
		play.libs.Files.copy(uploaded, toSave);//写入A目录添加的文件
		
		File bFile = new File(filePath + "b/");
		if (!bFile.exists()) {
			bFile.mkdirs();
		}
		bFile = new File(filePath + "b/" + fn + ".txt");
		if(bFile.exists()){//删除B目录原数据文件
			play.libs.Files.delete(bFile);
		}
		play.libs.Files.copy(toSave, bFile);//将A目录要替换到B目录的文件写到B目录
		checkFile.createNewFile();//重新创建校验文件
		return saveName;
	}