小编yev*_*yev的帖子

Java通用接口与通用方法,以及何时使用一个

我想知道,除了语法差异,何时会使用通用接口而不是接受通用参数的方法?

public interface Flight<T>{
   void fly(T obj);
}
Run Code Online (Sandbox Code Playgroud)

过度

public interface Flight{
    void <T> fly(T obj);
}
Run Code Online (Sandbox Code Playgroud)

java generics methods interface parameterized

16
推荐指数
1
解决办法
3070
查看次数

Java在Apache POI上进行搜索和替换时如何避免覆盖模板文件

我正在使用 Apache POI 3.13 并试图从给定的模板文件中搜索和替换文本,然后保存新生成的 .docx。这是我的代码:

public static void main(String[] args) throws InvalidFormatException, IOException {
    String filePath = "Sample.docx";
    File outputfile = new File("SampleProcessed.docx");

    XWPFDocument doc = new XWPFDocument(OPCPackage.open(filePath));

    for (XWPFParagraph p : doc.getParagraphs()) {
        List<XWPFRun> runs = p.getRuns();
        if (runs != null) {
            for (XWPFRun r : runs) {
                String text = r.getText(0);
                if (text != null && text.contains("$VAR")) {
                    text = text.replace("$VAR", "JohnDoe");
                    r.setText(text, 0);
                }
            }
        }
    }

    doc.write(new FileOutputStream(outputfile));
    doc.close();
    System.out.println("Done");
    Desktop.getDesktop().open(outputfile);
}
Run Code Online (Sandbox Code Playgroud)

这看起来很简单,但是当我运行这段代码时,文档“Sample.docx”也被替换了。最后,我有两个内容相同的文档。

这是 POI …

java apache-poi xwpf

3
推荐指数
1
解决办法
1105
查看次数

标签 统计

java ×2

apache-poi ×1

generics ×1

interface ×1

methods ×1

parameterized ×1

xwpf ×1