使用Java程序解析word文档里包含的图片信息

Java 专栏收录该内容
721 篇文章 4 订阅
package youdao;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class WordPictureExtractor {

	public final static String FOLDER = "C:\\Users\\i042416\\Pictures\\WORD\\";

	public static void main(String[] args) throws Exception {
		try {
			readZipFile("C:\\Users\\i042416\\Pictures\\1.docx");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void copyImage(String fileName, InputStream input) {
		try {
			String[] result = fileName.split("/");
			String outputFileName = FOLDER + result[2];
			FileOutputStream fileOutputStream = new FileOutputStream(new File(
					outputFileName));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = input.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}

			fileOutputStream.write(output.toByteArray());
			input.close();
			fileOutputStream.close();
			System.out.println("File: " + outputFileName
					+ " copied successfully!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void readZipFile(String file) throws Exception {
		ZipFile zf = new ZipFile(file);
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		ZipInputStream zin = new ZipInputStream(in);
		ZipEntry ze;
		while ((ze = zin.getNextEntry()) != null) {
			if (ze.isDirectory()) {
				continue;
			}
			String fileName = ze.getName();
			if (!fileName.contains("word/media/image"))
				continue;
			System.out.println(fileName + " : " + ze.getSize() + " bytes");
			long size = ze.getSize();
			if (size > 0) {
				InputStream image = zf.getInputStream(ze);
				copyImage(fileName, image);
			}
		}
		zin.closeEntry();
		zin.close();
		zf.close();
	}
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值