2

我有一个文档文件。我正在使用 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;
}
4

1 回答 1

1

最后我找到了在不丢失格式的情况下替换文本的方法。我用过Apache POI

这些是jar文件:

poi-3.9-20121203.jar,poi-scratchpad-3.9-20121203.jar

这是代码:

 try
{
    URL url = new URL("localhost:8080/testproject/downloads/fileName.doc");
    InputStream in = url.openStream();
    fs = new POIFSFileSystem(in);
    HWPFDocument doc = new HWPFDocument(fs);
    newFileName = request.getRealPath("") + "/downloads/newFile.doc";
    OutputStream writer = new FileOutputStream(newFileName);

    doc.getRange().replaceText("Location", "USA");
    doc.write(writer);
    writer.close();
}
catch(Exception e) 
{
    e.printStackTrace();
}
于 2013-10-09T05:49:11.430 回答