欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-27 17:17:20
...
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");
	}

}