一、新建word2007文檔h2do.docx;java
二、QQ截圖粘貼到文檔,添加些文字;web
三、用winrar打開(修改擴展名docx爲rar或右鍵->打開方式->選擇winrar程序),目錄結構以下:app
.code
│ [Content_Types].xmlxml
│圖片
├─docPropsip
│ app.xml文檔
│ core.xmlget
│it
├─word
│ │ comments.xml
│ │ document.xml
│ │ endnotes.xml
│ │ fontTable.xml
│ │ footnotes.xml
│ │ numbering.xml
│ │ settings.xml
│ │ styles.xml
│ │ webSettings.xml
│ │
│ ├─media
│ │ image1.png
│ │ image2.png
│ │
│ ├─theme
│ │ theme1.xml
│ │
│ └─_rels
│ document.xml.rels
│
└─_rels
.rels
如下代碼經過java程序替換word文件中的圖片image1.png
public static void main(String[] args) throws Throwable { ZipInputStream zis = new ZipInputStream (new FileInputStream ("h2do.docx") ); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("e2say.docx")); ZipEntry ze = null; byte[] b = new byte[1024]; while((ze = zis.getNextEntry()) != null) { System.out.println(ze.getName() + ":" + ze.getMethod()); ZipEntry entry = new ZipEntry(ze.getName()); zos.putNextEntry(entry); /*將源壓縮文件中每一個文件寫至新壓縮文件*/ InputStream is = zis; if(ze.getName().endsWith(".xml")) { String line = null; BufferedReader br = new BufferedReader(new InputStreamReader(is)); while((line = br.readLine()) != null) { //TODO:進行查證替換 zos.write((line+"\r\n").getBytes()); } }else{//非xml文件,二進制流數據 //替換圖片 if(ze.getName().endsWith("image1.png")){ is = new FileInputStream("temp.png"); } int r = -1; while((r = is.read(b)) != -1){ zos.write(b, 0, r); } } if(is != zis){ is.close(); } } zos.close(); }