文件修改和替换

统计指定字符串出现的次数,统计文本的行数,修改指定文件夹下的指定内容,并把修改后的文本另存到新的文件夹下,程序如下:

package cn.tedu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class UpdateTest {
	static String replaceAll = "";
	static String ReplaceAll = "";
	static String fileName = "E:/Test/My/microcore.txt";
	static String str = "我";
	static String aim = "风";
	static String outpath = "E:/Test/out/";
	static String file_Name = "newfile.text";
	public static void main(String[] args) throws Exception {
		System.out.println(str+"出现了"+getStringNumberMethod(fileName, str)+"次");
		replace();
		try {
			long currentTimeMillis = System.currentTimeMillis();
			file_Name = currentTimeMillis+file_Name;
			File outfile = new File(outpath+file_Name);//文件路径(路径+文件名)
			if (!outfile.exists()) {   //文件不存在则创建文件,先创建目录
				File dir = new File(outfile.getParent());
				dir.mkdirs();
				outfile.createNewFile();
			}
			FileOutputStream outStream = new FileOutputStream(outfile); //文件输出流将数据写入文件
			outStream.write(ReplaceAll.getBytes());
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("修改文件成功!"+"修改后的文件保存路径为:"+outpath+file_Name);
		}
	}

	public static String  replace() throws FileNotFoundException {
		int row = 0;
		BufferedReader br = new BufferedReader(new FileReader(fileName));
		String lineTxt = null;
		try {
			while((lineTxt = br.readLine()) != null){
				row++;
				replaceAll = lineTxt.replaceAll(str,aim);
				ReplaceAll = ReplaceAll+replaceAll+"\r\n";
			 }
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		System.out.println(str+"一共有"+row+"行");
		return ReplaceAll;
	}
	public static int getStringNumberMethod(String fileName, String str) throws Exception {
		int num = 0;
		BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
		String readLine = "";
		StringBuffer stringBuffer = new StringBuffer();
		while ((readLine = bufferedReader.readLine()) != null) {
			stringBuffer.append(readLine);
		}
		for (int i = 0; i < stringBuffer.length(); i++) {
			if (stringBuffer.indexOf(str, i) != -1) {
				i = stringBuffer.indexOf(str, i);
				num++;
			}
		}
		return num;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值