Java编程琐事(11)——文件的读取、替换和保存

实例程序:

package com.solid.fileoper;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.util.ArrayList;

import java.util.List;

/**

* 对某个目录下的html文件进行遍历,然后替换html文件中的源代码,然后保存修改之后的文件。

* @author solidwang

*

*/

public class FileReplace {

private String sourceStr1 = "/hqapp/tcm/3/attachments/paper";

private String replaceStr1 = "www.hq.unicom.local/tcm_unicom/tcm_unicom/3/attachments/paper";

private String sourceStr2 = "http://www.unicom.local/tcm/3/ewebeditor/uploadfile";

private String replaceStr2 = "http://www.unicom.local/tcm_unicom/3/ewebeditor/uploadfile";

private String sourceStr3 = "http://www.unicom.local/tcm/ewebeditor/uploadfile";

private String replaceStr3 = "http://www.unicom.local/tcm_unicom/3/ewebeditor/uploadfile";

/**

* 修改目录下的.html文件

* @param filePath 读取文件路径

* @param prefix 文件前缀

* @param savePath 文件保存路径

*/

public void modifyFileInDirectory(String filePath, String savePath, String prefix) {

List list = readFileInDirectory(filePath, prefix);

try {

for(int i=0; i<list.size(); i++) {

readFile(filePath + list.get(i), savePath + list.get(i));

System.out.println("读取了第" + (i+1) + "个文件,文件路径:" + filePath + list.get(i));

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 读取文件并替换其中的路径,然后保存文件

* @param filePath 读取文件路径

* @param savePath 保存文件路径

*/

public void readFile(String filePath, String savePath) {

BufferedReader br = null;

BufferedWriter bw = null;

String content = "";

try {

br = new BufferedReader(new FileReader(filePath));

bw = new BufferedWriter(new FileWriter(savePath));

String line;

while((line = br.readLine()) != null && (line != "")) {

content = line + br.readLine() + "\n";

bw.write(content.replaceAll(sourceStr1, replaceStr1).replaceAll(sourceStr2, replaceStr2).replaceAll(sourceStr3, replaceStr3).replaceAll("null", ""));

}

bw.flush();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if(br != null) br.close();

if(bw != null) bw.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

* 遍历某目录下的所有.html文件

* @param filePath

* @param prefix

* @return html文件名数组

*/

public List readFileInDirectory(String filePath, String prefix) {

File fileDir = new File(filePath);

File[] files = fileDir.listFiles();

List list = new ArrayList();

for(int i=0; i<files.length; i++) {

if(files[i].getName().startsWith("preview")) {

list.add(files[i].getName());

}

}

return list;

}

/**

* 测试方法

*/

public static void main(String[] args) {

FileReplace readFile = new FileReplace();

readFile.modifyFileInDirectory("D:/backup/中国联通V1.0/3/papers/", "D:/test/3/papers/", ".html");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值