天天看點

java文本内指定字元位置添加内容

package com.zhang.stream;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.util.LinkedList;
import java.util.List;

import com.zhang.common.Common;

/** 
* @Package com.zhang.stream 
* @ClassName: PubFileUtil 
* @Description: 讀寫有風險,操作需謹慎(注意備份)  
* @author: ZhangSongbo
* @date 2014-9-28 上午11:47:42 
* @version V1.0 
*/ 
public class PubFileUtil {

	private static String filePath = "d:\\EduInfo.java";
        public static final String RN = "\r\n";//可替換Common.RN

	/**
	 * @Title: readFileList
	 * @Description: 所給目錄下的所有檔案名稱集合
	 * @param @param filepath 檔案路徑
	 * @param @return   傳回目前路徑下所有檔案名稱集合
	 * @return List<String>   
	 * @throws IOException
	 */
	public static List<String> readFileList(String filepath) throws IOException {
		List<String> list = new LinkedList<String>();
		try {
			File file = new File(filepath);
			if (!file.isDirectory()) {
				System.out.println("檔案");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());

			} else if (file.isDirectory()) {
				System.out.println("檔案夾");
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "\\" + filelist[i]);
					if (!readfile.isDirectory()) {
						list.add(readfile.getName());
					} else if (readfile.isDirectory()) {
						readFileList(filepath + "\\" + filelist[i]);
						System.out.println(filepath + "\\" + filelist[i]);
					}
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(list);
		return list;

	}

	/**
	 * @Title: randomAccessWrite
	 * @Description: 随機流寫操作
	 * @param @param filePath 檔案路徑
	 * @param @param content  追加的内容 
	 * @return void   
	 * @throws IOException
	 */
	public static void randomAccessWrite(String filePath, String content) {
		File fileName = new File(filePath);
		RandomAccessFile randomFile = null;
		try {
			// 打開一個随機通路檔案流,按讀寫方式
			randomFile = new RandomAccessFile(fileName, "rw");
			// 檔案長度,位元組數
			long fileLength = randomFile.length();
			// 将寫檔案指針移到檔案尾。
			// byte[] buffer = new byte[1024];
			randomFile.seek(fileLength);
			randomFile.write(content.getBytes());
			System.out.println("操作完成!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @Title: findLines
	 * @Description: TODO
	 * @param @param filePath 檔案路徑
	 * @param @param context 查找的字元串
	 * @param @return 包含搜尋的字元串的行
	 * @param @throws IOException   
	 * @return List<String>   
	 */
	public static List<String> findLines(String filePath, String context) throws IOException {
		List<String> list = new LinkedList<String>();
		BufferedReader read = new BufferedReader(new FileReader(filePath));
		String str = null;
		while ((str = read.readLine()) != null) {
			if (str.indexOf(context) != -1) {
				list.add(str);
			}
		}
		read.close();
		return list;
	}

	/**
	 * @Title: findParagraph
	 * @Description: 根據查找字元串劃分内容(第一個符合的字元串對象有效)
	 * @param @param filePath 檔案路徑
	 * @param @param context 查找的字元串
	 * @param @return List<String>
	 * @param @throws IOException   
	 * @return List<String>   
	 * @throws
	 */
	public static List<String> findParagraph(String filePath, String context) throws IOException {
		BufferedReader read = new BufferedReader(new FileReader(filePath));
		List<String> list = new LinkedList<String>();
		String paragraphHead = "";
		String paragraphEnd = "";
		String line = "";
		int index = 0;
		int lineNum=1;
		while ((line = read.readLine()) != null) {
			if (index == 0) {
				paragraphHead += (line + Common.RN);
			}
			if (line.indexOf(context) != -1 && index == 0) {
				System.out.println("行号:"+lineNum+",目前行内容: "+line);
				list.add(paragraphHead);
				index++;
				continue;
			}
			if (index > 0) {
				paragraphEnd += (line + Common.RN);
			}
			lineNum++;
		}
		list.add(paragraphEnd);
		read.close();
		return list;
	}

	/**
	 * @Title: writeFile
	 * @Description: TODO
	 * @param @param filePath 檔案路徑名稱
	 * @param @param context要寫入的檔案内容
	 * @param @param codeType編碼格式(預設為utf-8)
	 * @param @throws IOException   
	 * @return void   
	 * @throws IOException
	 */
	public static void writeFile(String filePath, String context, String codeType) throws IOException {
		File f = new File(filePath);
		InputStreamReader read = null;
		if (codeType != null && !codeType.trim().equals("")) {
			read = new InputStreamReader(new FileInputStream(f), codeType);
		} else {
			read = new InputStreamReader(new FileInputStream(f), "UTF-8");
		}
		BufferedReader reader = new BufferedReader(read);
		String line = "";
		String str = "";
		while ((line = reader.readLine()) != null) {
			str += (line + Common.RN);
		}
		OutputStream out = new FileOutputStream(f);
		byte[] bt = context.getBytes();
		out.write(bt);
		out.flush();
		out.close();
		System.out.println("讀取檔案結束!" + Common.RN + "開始向檔案開始追加内容" + Common.RN + str);
		randomAccessWrite(filePath, str);

	}

	/**
	 * @Title: writeParagraph
	 * @Description: TODO
	 * @param @param filePath 路徑
	 * @param @param context 要查找的字元串
	 * @param @param wcontext要寫入的内容
	 * @param @param codeType 編碼格式(預設utf-8)
	 * @param @throws IOException   
	 * @return void   
	 * @throws
	 */
	public static void writeParagraph(String filePath, String context, String wcontext, String codeType) throws IOException {
		File fileName = new File(filePath);
		List<String> list = findParagraph(filePath, context);
		RandomAccessFile randomFile = null;
		OutputStreamWriter write = null;
		if (codeType != null && !codeType.trim().equals("")) {
			write = new OutputStreamWriter(new FileOutputStream(fileName), codeType);
		} else {
			write = new OutputStreamWriter(new FileOutputStream(fileName), "utf-8");
		}
		//清空檔案内容
		write.write("");
		write.close();
		try {
			// 打開一個随機通路檔案流,按讀寫方式
			randomFile = new RandomAccessFile(fileName, "rw");
			int index=0;
			for (int i = 0; i < list.size(); i++) {
				if (index==0) {
					randomFile.write(list.get(i).getBytes());
					randomFile.write((wcontext + Common.RN).getBytes());
				}
				if (index>0) {
					randomFile.write(list.get(i).getBytes());
				}
				index++;
			}
			System.out.println("操作完成!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String[] args) throws IOException {
		long startTime = System.currentTimeMillis();
		writeParagraph( filePath,  "{",  "做人要像陳冠希,随時帶好照相機!",  null);
		long endTime= System.currentTimeMillis();
		System.out.println("time:"+(endTime-startTime)+"ms");
		//readFileList("D:\\Workspaces\\dao\\src");
	}

}