有三種方式實現(xiàn)java壓縮:
成都創(chuàng)新互聯(lián)公司是專業(yè)的網(wǎng)站建設(shè)公司,提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)站設(shè)計等網(wǎng)站開發(fā)一體化解決方案;包括H5頁面制作,小程序定制開發(fā),網(wǎng)站定制,企業(yè)網(wǎng)站建設(shè),成都商城網(wǎng)站開發(fā),成都響應(yīng)式網(wǎng)站建設(shè),建網(wǎng)站,PHP網(wǎng)站建設(shè),軟件開發(fā),軟文平臺,網(wǎng)站營銷。歡迎做網(wǎng)站的企業(yè)前來合作洽談,成都創(chuàng)新互聯(lián)公司將竭誠為您服務(wù)!
1、jdk自帶的包java.util.zip.ZipOutputStream,不足之處,文件(夾)名稱帶中文時,出現(xiàn)亂碼問題,實現(xiàn)代碼如下:
/**
* 功能:把 sourceDir 目錄下的所有文件進(jìn)行 zip 格式的壓縮,保存為指定 zip 文件
* @param sourceDir 如果是目錄,eg:D:\\MyEclipse\\first\\testFile,則壓縮目錄下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,則只壓縮本文件
* @param zipFile 最后壓縮的文件路徑和名稱,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 創(chuàng)建寫出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);
String basePath = null;
// 獲取目錄
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}
zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}
return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}
InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}
}
2、使用org.apache.tools.zip.ZipOutputStream,代碼如下,
package net.szh.zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipCompressor {
static final int BUFFER = 8192;
private File zipFile;
public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
/* 判斷是目錄還是文件 */
if (file.isDirectory()) {
System.out.println("壓縮:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("壓縮:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}
/** 壓縮一個目錄 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
for (int i = 0; i files.length; i++) {
/* 遞歸 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}
/** 壓縮一個文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3、可以用ant中的org.apache.tools.ant.taskdefs.Zip來實現(xiàn),更加簡單。
package net.szh.zip;
import java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
public class ZipCompressorByAnt {
private File zipFile;
public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File srcdir = new File(srcPathName);
if (!srcdir.exists())
throw new RuntimeException(srcPathName + "不存在!");
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夾 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); 排除哪些文件或文件夾
zip.addFileset(fileSet);
zip.execute();
}
}
測試一下
package net.szh.zip;
public class TestZip {
public static void main(String[] args) {
ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
zc.compress("E:\\test");
ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");
zca.compress("E:\\test");
}
}
樓主是說解壓了的文件大小只有33.1MB,但是卻占了51.2MB的空間嗎?
如果是這個意思的話,那我要告訴樓主,首先這個問題和JAVA沒有關(guān)系,根據(jù)你的截圖,可以斷定你用的是FAT32文件系統(tǒng)。這只是文件存儲的形式,很正常。
簡單的說,磁盤存儲數(shù)據(jù)的最小單位是簇,比方說你的簇大小為128K,一個簇只能存放一個文件,然后你的一個文件只有16K,它占了這個簇,然后還有112K沒有用,是吧。但是那112K就不能再存放其它文件了。如果要存放其它文件,就要占另一個簇。
樓主,懂了吧,這跟簇的大小有關(guān),但是也不是簇越小越好,簇越小,讀寫性能都有所下降。這是正?,F(xiàn)象。如果你非覺得不舒服,那就用NTFS文件系統(tǒng)吧,把壓縮打開,就不會有這種情況了,希望對你有幫助
可以使用Draw這個類,通過改變像素來改變存儲大小,實例如下:
public?static?boolean?compressPic(String?srcFilePath,?String?descFilePath)?throws?IOException?{
File?file?=?null;
BufferedImage?src?=?null;
FileOutputStream?out?=?null;
ImageWriter?imgWrier;
ImageWriteParam?imgWriteParams;
//?指定寫圖片的方式為?jpg
imgWrier?=?ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams?=?new?javax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
//?要使用壓縮,必須指定壓縮方式為MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
//?這里指定壓縮的程度,參數(shù)qality是取值0~1范圍內(nèi),
imgWriteParams.setCompressionQuality((float)?1);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModel?colorModel?=ImageIO.read(new?File(srcFilePath)).getColorModel();//?ColorModel.getRGBdefault();
//?指定壓縮時使用的色彩模式
//????????imgWriteParams.setDestinationType(new?javax.imageio.ImageTypeSpecifier(
//????????????????colorModel,?colorModel.createCompatibleSampleModel(16,?16)));
imgWriteParams.setDestinationType(new?javax.imageio.ImageTypeSpecifier(
colorModel,?colorModel.createCompatibleSampleModel(16,?16)));
try?{
if?(isBlank(srcFilePath))?{
return?false;
}?else?{
file?=?new?File(srcFilePath);System.out.println(file.length());
src?=?ImageIO.read(file);
out?=?new?FileOutputStream(descFilePath);
imgWrier.reset();
//?必須先指定?out值,才能調(diào)用write方法,?ImageOutputStream可以通過任何
//?OutputStream構(gòu)造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
//?調(diào)用write方法,就可以向輸入流寫圖片
imgWrier.write(null,?new?IIOImage(src,?null,?null),
imgWriteParams);
out.flush();
out.close();
}
}?catch?(Exception?e)?{
e.printStackTrace();
return?false;
}
return?true;
}
public?static?boolean?isBlank(String?string)?{
if?(string?==?null?||?string.length()?==?0?||?string.trim().equals(""))?{
return?true;
}
return?false;
}