我有一个文档文件。我正在使用 Java 程序将“位置”一词替换为“美国”。但是 doc 文件会丢失其格式。
这是我的代码:
replaceText(String path, String fileName, String text, HttpServletRequest request) {
String newFileName = null;
POIFSFileSystem fs = null;
try
{
URL url = new URL(path+"/doc/"+fileName);
InputStream in = url.openStream();
fs = new POIFSFileSystem(in);
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
newFileName = request.getRealPath("") + "/doc/"+text+".doc";
OutputStream writer= new FileOutputStream(newFileName);
String[] paragraphs = we.getParagraphText();
for( int i=0; i<paragraphs .length; i++ ) {
paragraphs[i] = paragraphs[i].replaceAll("location",text);
byte[] contentInBytes = paragraphs[i].getBytes();
writer.write(contentInBytes);
}
writer.close();
}
catch(Exception e) {
e.printStackTrace();
}
return newFileName;
}