一、核心代码分析:
spire.doc官网: https://www.e-iceblue.com/
import com.spire.doc.Document;
//import javax.swing.text.Document;
import com.spire.doc.FileFormat;
Document document = new Document(file.getPath());
//使用新文本替换文档中的指定文本,参数1为源,参数2为替换后的内容
document.replace(key, map.get(key), false, true);
//替换后的文档保存文档
document.saveToFile("D:\\替换工具\\目标文件\\"+file.getName(), FileFormat.Docx_2013);
二、 完整实现
package com.example.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.spire.doc.Document;
//import javax.swing.text.Document;
import com.spire.doc.FileFormat;
/**
*author:bingbing
*日期:2020年6月27日
*时间:下午4:29:08
*/
public class ReplaceWordContent {
public static void main(String[] args) throws IOException {
String directory="D:\\替换工具\\源文件";
//获取到所有的file
File directoryFile=new File(directory);
File [] lists=directoryFile.listFiles();
System.out.println("包含的文件有:"+Arrays.toString(lists));
for(int i=0;i<lists.length;i++) {
replaceWordMutilFiles(lists[i]);
}
System.out.println("替换完毕!");
}
private static void replaceWordMutilFiles(File file) throws IOException {
Document document = new Document(file.getPath());
File source=new File("D:\\替换工具\\查找内容-替换内容.txt");
//读取出需要替换的文件内容
// 查找内容 替换内容
// 毛永 BBB
InputStreamReader reader = new InputStreamReader(new FileInputStream(source),"UTF-8");
BufferedReader bufIn = new BufferedReader(reader);
String line=null;
Map<String,String> map=new HashMap<String,String>();
int count=0;
while ( (line = bufIn.readLine()) != null) {
count++;
// 替换每行中, 符合条件的字符串
System.out.println("行:"+line);
if(line!=null&&line!="") {
String str[]=line.split(" ");
System.out.println("分割后的数组:"+Arrays.toString(str)+"长度为:"+str.length);
if(count!=1&&str.length!=1) {
map.put(str[0], str[str.length-1]);
}
}
}
System.out.println("需要替换的内容为:"+map);
//替换所有文件下的对应的Key个value
//使用新文本替换文档中的指定文本,参数1为源,参数2为替换后的内容
//遍历map,获取Key和value
Set<String> keys = map.keySet(); //此行可省略,直接将map.keySet()写在for-each循环的条件中
for(String key:keys){
System.out.println("key值:"+key+" value值:"+map.get(key));
//批量替换文件
document.replace(key, map.get(key), false, true);
}
//保存文档
document.saveToFile("D:\\替换工具\\目标文件\\"+file.getName(), FileFormat.Docx_2013);
}
}