如何使用JAVA代码压缩PDF文件

Python022

如何使用JAVA代码压缩PDF文件,第1张

用java代码压缩应用到程序了,代码一般是比较复杂的,对pdf文件的mate标签优化,这类标签包括三类,pdf文件不是网页就是个文件,何况我们可以用pdf压缩工具压缩,下面有个解决方法,楼主可以做参照。

1:点击打开工具,打开主页面上有三个功能进行选择,我们选择pdf文件压缩。

2:这这个页面中我们选择pdf文件在这里打开,点击“添加文件”按钮将文件添加进来。

3:然后在页面中点击“开始压缩”就可以开始压缩文件了。

4:压缩完成的文件页面会显示已经完成。

package com.javatest.techzero.gui  

 import java.io.File

import java.io.FileInputStream

import java.io.FileOutputStream

import java.io.InputStream

import java.io.OutputStream

import java.util.zip.ZipEntry

import java.util.zip.ZipFile

import java.util.zip.ZipInputStream 

 public class ZipFileDemo {

 @SuppressWarnings("resource")

 public static void main(String args[]) throws Exception {

  File file = new File("d:" + File.separator + "test.zip")

  File outFile = null

  ZipFile zipFile = new ZipFile(file)

  ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file))

  ZipEntry entry = null

  InputStream input = null

  OutputStream out = null

  while ((entry = zipInput.getNextEntry()) != null) {

   System.out.println("开始解压缩" + entry.getName() + "文件。。。")

   outFile = new File("d:" + File.separator + entry.getName())

   if (!outFile.getParentFile().exists()) {

    outFile.getParentFile().mkdir()

   }

   if (!outFile.exists()) {

    outFile.createNewFile()

   }

   input = zipFile.getInputStream(entry)

   out = new FileOutputStream(outFile)

   int temp = 0

   while ((temp = input.read()) != -1) {

   <SPAN style="WHITE-SPACE: pre"> </SPAN>//System.out.println(temp)

    out.write(temp)

   }

   input.close()

   out.close()

  }

  System.out.println("Done!")

 }

}

仅供参考

下面的示例代码演示如何创建zip压缩包。

首先需要由需要压缩的文件创建一个InputStream对象,然后读取文件内容写入到ZipOutputStream中。

ZipOutputStream类接受FileOutputStream作为参数。创建号ZipOutputStream对象后需要创建一个zip entry,然后写入。

import java.io.FileInputStream

import java.io.FileOutputStream

import java.io.IOException

import java.util.zip.ZipEntry

import java.util.zip.ZipOutputStream

/**

*

* @author outofmemory.cn

*/

public class Main {

/**

* Creates a zip file

*/

public void createZipFile() {

try {

String inputFileName = "test.txt"

String zipFileName = "compressed.zip"

//Create input and output streams

FileInputStream inStream = new FileInputStream(inputFileName)

ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName))

// Add a zip entry to the output stream

outStream.putNextEntry(new ZipEntry(inputFileName))

byte[] buffer = new byte[1024]

int bytesRead

//Each chunk of data read from the input stream

//is written to the output stream

while ((bytesRead = inStream.read(buffer)) >0) {

outStream.write(buffer, 0, bytesRead)

}

//Close zip entry and file streams

outStream.closeEntry()

outStream.close()

inStream.close()

} catch (IOException ex) {

ex.printStackTrace()

}

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

new Main().createZipFile()

}