日期:2014-05-20 浏览次数:20875 次
/** * */ package com.ecc.test1016; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; /** * @author Liu Shijie * */ public class ReplaceString { String path = "C:\\j2sdk1.4.2\\README.txt"; File file; File file_bak; FileReader fr; BufferedReader br; FileOutputStream os; /** * */ public ReplaceString() { file = new File(path); file_bak = new File(file.getPath()+file.getName()+".bak"); } public void doReplace() { if (file.exists()) { try { fr = new FileReader(file); br = new BufferedReader(fr); os = new FileOutputStream(file_bak); String line = ""; String line_bak = ""; while ((line = br.readLine()) != null) { if(line.indexOf("course_name =")!=-1){ System.out.println(line); line = line.replaceAll("course_name = \"123123\"", "course_name = \"555555\""); System.out.println(line_bak); } os.write(line.getBytes(), 0, line.getBytes().length); os.write("\n".getBytes()); } fr.close(); br.close(); os.close(); file.delete(); file_bak.renameTo(new File(path)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new ReplaceString().doReplace(); } }
------解决方案--------------------
import java.io.*; /** * 指定文件内容的替换,输出到新文件 * @author 张斌(小神) * */ public class ReplaceString_File { /** * * @param pathName : 读取文件路径 * @param newPathName : 输出文件路径 * @param course : 要修改的字串 * @param value : 新字串 * @throws IOException */ public void replaceString(String pathName, String newPathName, String course, String value) throws IOException { File file = new File(pathName); File file_output = new File(newPathName); if (file.exists()) { BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(newPathName)); String context; while ((context = br.readLine()) != null) { context.replace(course, value); bw.write(context); bw.newLine(); //System.out.println(context); } bw.flush(); br.close(); bw.close(); } } public static void main(String[] args) { ReplaceString_File rsf = new ReplaceString_File(); try { rsf.replaceString("F:\\321.txt", "F:\\123.txt", "def=456", "def=654"); } catch (IOException e) { e.printStackTrace(); } } }