1.需求:有一个文件:D:\tmp\falvkuaiche-seed.txt,需要在此文件的每一行的最后都要加上index.hmtl这个字符串并写入新文件D:\tmp\falvkuaiche-seed-done.txt中。
内容:
http://www.lawtime.cn/info/hunyin/ccfglhccfg/
http://www.lawtime.cn/info/hetong/baozheng/
http://www.lawtime.cn/info/sunhai/shzhishi/
2.编写处理类:
package com.dada.utils.fileHandler;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class AppendStrToEachLineEnd {
public static void main(String[] args) {
addStr("d:\\tmp\\falvkuaiche-seed.txt", "index.html","d:\\tmp\\falvkuaiche-seed-done.txt");
}
/**
* 为指定文本文件的的每一行的结尾添加指定字符串并写入新文件中
*
* @param filePath
* 文件位置
* @param appendStr
* 添加内容
*/
public static void addStr(String sourceFilePath, String appendStr,String destFilePath) {
File fileReaded = new File(sourceFilePath);
try {
//定义读取文件
FileReader fr = new FileReader(fileReaded);
BufferedReader br = new BufferedReader(fr);
String content = br.readLine();
//定义写出文件
FileWriter fw = new FileWriter(destFilePath);
BufferedWriter bw = new BufferedWriter(fw);
while (content != null) {
System.out.println("读入内容:\t" + content);
System.out.println("写出内容:\t"+content+appendStr);
if(content.indexOf(appendStr)>0) {
bw.write(content+"\n");
} else {
bw.write(content+appendStr+"\n");
}
content = br.readLine();
}
fw.flush();
bw.flush();
fw.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.处理结果:
http://www.lawtime.cn/info/hunyin/ccfglhccfg/index.html
http://www.lawtime.cn/info/hetong/baozheng/index.html
http://www.lawtime.cn/info/sunhai/shzhishi/index.html