统计指定字符串出现的次数,统计文本的行数,修改指定文件夹下的指定内容,并把修改后的文本另存到新的文件夹下,程序如下:
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;
}
}