public class ModifyContent {
/**
* @param args
*/
public static void main(String[] args) throws IOException,
UnsupportedEncodingException {
List<String> list = readFileContent();
List<String> chapterlist = getChapterNames();
Map<String, String> chapterMap = new HashMap<String, String>();
for (int i = 0; i < chapterlist.size(); i++) {
chapterMap.put(chapterlist.get(i), list.get(i));
}
BookMusicBean.getInstance().setMap(chapterMap);
Map<String, String> targetMap = BookMusicBean.getInstance().getMap();
String to = "";
String from = "";
for (int i = 0; i < chapterlist.size(); i++) {
from = chapterlist.get(i);
to = targetMap.get(chapterlist.get(i));
System.out.println("to=" + to + ",from=" + from);
replace("d:/chen2010.txt", from, to);
}
// replace("d:/chen2010.txt", "###第2章 月蚀天涯", "1234564879879");
}
/**
*
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static List<String> readFileContent() throws IOException,
UnsupportedEncodingException {
// String[] chapterArrays=new
List<String> chapters = new ArrayList<String>();
File infile = new File("d:/chen.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(infile), "utf-8"));
while (in.read() != -1) {
String target = in.readLine();
if (target.startsWith("##第")) {
chapters.add(target);
}
}
return chapters;
}
public static List<String> getChapterNames() throws IOException,
UnsupportedEncodingException {
List<String> chapterNames = new ArrayList<String>();
File files = new File("F:/Music"); // 指定文件名及路径
for (String file : files.list()) {
File tempFile = new File(files + "\\" + file);
String fileName = tempFile.getName();
String suffix = fileName.substring(0, fileName.lastIndexOf("."));
chapterNames.add(suffix);
}
return chapterNames;
}
public static void replace(String infilename, String from, String to)
throws IOException, UnsupportedEncodingException {
File infile = new File(infilename);
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(infile), "gbk"));
File outfile = new File(infile + ".txt");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(outfile), "gbk")));
String reading;
while ((reading = in.readLine()) != null) {
out.println(reading.replaceAll(from, to));
}
out.close();
in.close();
infile.delete();
outfile.renameTo(infile);
}
}