你好,由于內(nèi)容比較多,先概述一下先。如圖所示,為我寫的一個(gè)壓縮軟件,原理是利用哈弗曼算法實(shí)現(xiàn)的。我將資料整理好稍后就發(fā)到你郵箱,但在這里簡要說明一下代碼。
創(chuàng)新互聯(lián)主營古縣網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,手機(jī)APP定制開發(fā),古縣h5微信小程序搭建,古縣網(wǎng)站營銷推廣歡迎古縣等地區(qū)企業(yè)咨詢
請看我的空間
中的文章共5篇(太長了)
1.HuffmanTextEncoder類完成壓縮功能,可直接運(yùn)行,壓縮測試用文本文件。
2.HuffmanTextDecoder類完成解壓縮功能,可直接運(yùn)行,解壓縮?壓縮后的文本文件。
3.BitReader,工具類,實(shí)現(xiàn)對BufferedInputStream的按位讀取。
4.BitWriter,工具類,實(shí)現(xiàn)按位寫入的功能。該類來自網(wǎng)絡(luò)。
5.MinHeapT?,模板工具類,實(shí)現(xiàn)了一個(gè)最小堆。生成Huffman樹時(shí)使用。
package?com.io2.homework;
import?java.io.File;
import?java.io.FileInputStream;
import?java.io.FileNotFoundException;
import?java.io.FileOutputStream;
import?java.io.IOException;
import?java.util.zip.ZipEntry;
import?java.util.zip.ZipOutputStream;
/*壓縮文件夾*/
public?class?MyMultipleFileZip?
{
private?String?currentZipFilePath?=?"F:/MyZip.zip";
private?String?sourceFilePath;
private?ZipOutputStream?zos;
private?FileInputStream?fis;
public?MyMultipleFileZip(String?sourceFilePath)?
{
try
{
this.sourceFilePath?=?sourceFilePath;
zos?=?new?ZipOutputStream(new?FileOutputStream(currentZipFilePath));
//設(shè)定文件壓縮級別
zos.setLevel(9);
}?catch?(FileNotFoundException?e)?
{
e.printStackTrace();
}
}
//?在當(dāng)前條目中寫入具體內(nèi)容
public?void?writeToEntryZip(String?filePath)?
{
try
{
fis?=?new?FileInputStream(filePath);
}?catch?(FileNotFoundException?e1)?
{
e1.printStackTrace();
}
byte[]?buff?=?new?byte[1024];
int?len?=?0;
try?
{
while?((len?=?fis.read(buff))?!=?-1)
{
zos.write(buff,?0,?len);
}
}?catch?(IOException?e)?
{
e.printStackTrace();
}finally
{
if?(fis?!=?null)
try?
{
fis.close();
}?catch?(IOException?e)?
{
e.printStackTrace();
}
}
}
//?添加文件條目
public?void?addFileEntryZip(String?fileName)?
{
try?
{
zos.putNextEntry(new?ZipEntry(fileName));
}?catch?(IOException?e)?
{
e.printStackTrace();
}
}
public?void?addDirectoryEntryZip(String?directoryName)
{
try?
{
zos.putNextEntry(new?ZipEntry(directoryName?+?"/"));
}?catch?(IOException?e)
{
e.printStackTrace();
}
}
//?遍歷文件夾
public?void?listMyDirectory(String?filePath)
{
File?f?=?new?File(filePath);
File[]?files?=?f.listFiles();
if(files!=null)
{
for?(File?currentFile?:?files)?
{
//?設(shè)置條目名稱(此步驟非常關(guān)鍵)
String?entryName=?currentFile.getAbsolutePath().split(":")[1].substring(1);
//?獲取文件物理路徑
String?absolutePath?=?currentFile.getAbsolutePath();
if?(currentFile.isDirectory())?
{
addDirectoryEntryZip(entryName);
//進(jìn)行遞歸調(diào)用
listMyDirectory(absolutePath);
}
else?
{
addFileEntryZip(entryName);
writeToEntryZip(absolutePath);
}
}
}
}
//?主要流程
public?void?mainWorkFlow()
{
listMyDirectory(this.sourceFilePath);
if(zos!=null)
try?
{
zos.close();
}?catch?(IOException?e)?
{
e.printStackTrace();
}
}
public?static?void?main(String[]?args)?
{
new?MyMultipleFileZip("F:/fountainDirectory").mainWorkFlow();
}
}
有三種方式實(shí)現(xiàn)java壓縮:
1、jdk自帶的包java.util.zip.ZipOutputStream,不足之處,文件(夾)名稱帶中文時(shí),出現(xiàn)亂碼問題,實(shí)現(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);
}
}
/** 壓縮一個(gè)目錄 */
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() + "/");
}
}
/** 壓縮一個(gè)文件 */
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來實(shí)現(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");
}
}
可以使用 Runtime 直接調(diào)用 winRar 的命令行命令來解壓縮
注意:
1、winRar命令使用,在dos下輸入 unrar 就可以看到全部的命令說明。該命令在winRar的安裝目錄下
2、winRar命令行命令的路徑問題,也就是path。要么加入系統(tǒng)變量path中,要么在winRar的安裝目錄下執(zhí)行程序
以下是程序代碼,解壓 test.rar 到當(dāng)前目錄下,密碼123
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestRunTime {
public static void main(String[] args) {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("unrar e test.rar -p123");//執(zhí)行解壓縮命令
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null)
System.out.println(lineStr);
// 檢查命令是否執(zhí)行失敗。
if (p.waitFor() != 0) {
if (p.exitValue() == 1)// p.exitValue()==0表示正常結(jié)束,1:非正常結(jié)束
System.err.println("命令執(zhí)行失敗!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
再 windows下通過 cmd命令執(zhí)行解壓縮沒問題,但是通過 java代碼去執(zhí)行不能解壓是為什么?我在開始運(yùn)行中輸入命令: cmd/ c rar. exe x- y d:\\ auto. rar d:\\----上面命令可以解壓成功,但是通過下面 java代碼不能實(shí)現(xiàn)解壓縮功能,請指點(diǎn)。主要代碼: java. lang. Runtime. getRuntime(). exec(" cmd/ c rar. exe x- y d:\\ auto. rar d:\\");
再 windows下通過 cmd命令執(zhí)行解壓縮沒問題,但是通過 java代碼去執(zhí)行不能解壓是為什么?我在開始運(yùn)行中輸入命令: cmd/ c rar. exe x- y d:\\ auto. rar d:\\----上面命令可以解壓成功,但是通過下面 java代碼不能實(shí)現(xiàn)解壓縮功能,請指點(diǎn)。主要代碼: java. lang. Runtime. getRuntime(). exec(" cmd/ c rar. exe x- y d:\\ auto. rar d:\\");
分享標(biāo)題:java解壓縮算法代碼 字符串壓縮算法java
文章源于:http://muchs.cn/article18/doccdgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、手機(jī)網(wǎng)站建設(shè)、做網(wǎng)站、定制開發(fā)、搜索引擎優(yōu)化、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)