根据路径替换String
package com.chenjin.study.file;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.LineNumberReader;/** * <p>标题: 替换文件夹内字符串</p> * <p>说明: </p> * <p>版本: Copyright (c) 2008-11-11</p> * <p>创建: 2008-11-11 上午08:38:42 * @author cj */public class ReplaceString {/** 缓冲区大小 */private static final int SIZE = 8 * 1024;/** * <p>【按路径替换】</p> * @param path * @param oldStr * @param newStr * @author:cj */public static void replaceByPath(String path, String oldStr, String newStr) {File file = new File(path);if (!file.exists()) {System.err.println((new StringBuilder("file not found: ")).append(path).toString());return;} else {replaceByFile(file,oldStr,newStr);}}/** * <p>【按文件替换,可以为文件夹】</p> * * @param file * @param oldStr * @param newStr * @author:cj */public static void replaceByFile(File file, String oldStr, String newStr){if(file==null||oldStr==null||oldStr.equalsIgnoreCase(""))return ;if(file.isDirectory()){ File files[] = file.listFiles(); for(int i = 0; i < files.length; i++) replaceByFile(files, oldStr,newStr); return;}FileInputStream input = null;LineNumberReader reader = null; FileWriter fw = null; StringBuffer buffer = new StringBuffer();try {input = new FileInputStream(file);// 读数据reader = new LineNumberReader(new InputStreamReader(input), SIZE);String s = null;while ((s = reader.readLine()) != null) {buffer.append(replaceByString(s, oldStr ,newStr)).append("\n");}fw = new FileWriter(file); fw.write(buffer.toString());} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch(Exception e){e.printStackTrace();} finally {if (reader != null) {try { fw.close();reader.close();} catch (IOException e) {}catch(Exception e){}}if (input != null) {try {input.close();} catch (IOException e) {}catch(Exception e){}}}}public static String replaceByString(String str,String oldStr,String newStr) {return str.replaceAll(oldStr, newStr);}public static void main(String[] args) {String path="D:/zycms/wwwroot/jhzfxxgk/web";ReplaceString.replaceByPath(path, "src", "src=");}}感觉不是很好,希望能在取出文件同时改变。
页:
[1]