⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jar.java

📁 java压缩原理代码
💻 JAVA
字号:
/** Jar and UnJar
* Anyone can use this file freely
*
* Last updated by Sterntaler 2003-12-17

* faults: Could not resolve Unicode filename while jar
*/

/* ---------------------------------------------
// example: TestJar.java

package util.compress;

public class TestJar implements Jar.ProgressListener{
	public void JarProcessBegin(int totalFiles, long totalSize){
		System.out.println("Begin, Total: " + totalFiles + " files, " + totalSize / 1024 + "K");
	}
	public void JarProcess(int totalFiles, long totalSize, long fileSize){
		System.out.println("Current size: " + fileSize);
	}
	public void JarProcessEnd(int totalFiles, long totalSize){
		System.out.println("Operation Completed.");
	}
	
	public static void main(String[] args){
		TestJar test = new TestJar();
		Jar jar = new Jar();
		jar.addProgressListener(test);
		jar.jar("d:\\clock", "e:\\clk.jar");
	}
}
*/

package util.compress;

import java.util.ArrayList;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.JarInputStream;


public class Jar{
	final int BUF_SIZE = 1024 * 64;
	private int[] m_totalFiles = {0}; // for progress suport
	private long[] m_totalSize = {0};
	
	private ArrayList progressListeners = null;
	
	public Jar(){
		progressListeners = new ArrayList();
	}
	
	public void addProgressListener(ProgressListener pl){
		progressListeners.add(pl);
	}
	
	public void removeProgressListener(ProgressListener pl){
		progressListeners.remove(progressListeners.indexOf(pl));
	}
	
	private void onProgressBegin(int totalFiles, long totalSize){
		if (!progressListeners.isEmpty()){
			for (int i = 0; i < progressListeners.size(); i++){
				ProgressListener pl = (ProgressListener)progressListeners.get(i);
				pl.JarProcessBegin(totalFiles, totalSize);
			}
		}
	}
	
	private void onProgressEnd(int totalFiles, long totalSize){
		if (!progressListeners.isEmpty()){
			for (int i = 0; i < progressListeners.size(); i++){
				ProgressListener pl = (ProgressListener)progressListeners.get(i);
				pl.JarProcessEnd(totalFiles, totalSize);
			}
		}
	}
	
	private void onProgress(int totalFiles, long totalSize, long fileSize){
		if (!progressListeners.isEmpty()){
			for (int i = 0; i < progressListeners.size(); i++){
				ProgressListener pl = (ProgressListener)progressListeners.get(i);
				pl.JarProcess(totalFiles, totalSize, fileSize);
			}
		}
	}
	
	/** Get all summaray information of the directory.
	* @param dir The given directory
	* @param totalFiles Retrives file count of the directory
	* @param totalSize Retrives sum file size of the directory
	* @return true if successfully retrieves the values.
	*/
	boolean sumFileSize(String dir, int[] totalFiles, long[] totalSize){
		File file = null;
		try {
			file = new File(dir);
			File[] files = file.listFiles();
			if (files == null){
				if (!file.isDirectory()){ totalFiles[0]++; totalSize[0] += file.length(); }
			} else for (int i = 0; i < files.length; i++){
				if (files[i].isDirectory() && !files[i].getName().equals(".") && !files[i].getName().equals(".."))
					sumFileSize(files[i].getPath(), totalFiles, totalSize);
				else { totalFiles[0]++; totalSize[0] += files[i].length(); }
			}
			return true;
		} catch (Exception e){ return false; }
	}
	
	boolean sumFileSize(String[] dirs, int[] totalFiles, long[] totalSize){
		int[] fileCount = {0};
		long[] fileSize = {0};
		if (dirs == null || dirs.length < 1) return false;
		
		for (int i = 0; i < dirs.length; i++){
			sumFileSize(dirs[i], fileCount, fileSize);
			totalFiles[0] += fileCount[0];
			totalSize[0] += fileSize[0];
			fileCount[0] = 0; fileSize[0] = 0;
		}
		return true;
	}
	
	/** Get information from jar file
	* @param jarFile target jar file
	* @param totalFiles To retrieve total file count
	* @param totalSize To retrieve total file size
	* @return true if no error occurs.
	*
	* Did not work probably
	*/
	private boolean getJarFileInfo(String jarFile, int[] totalFiles, long[] totalSize){
		try {
			JarInputStream jis = new JarInputStream(new FileInputStream(jarFile));
			ZipEntry ze;
			while ((ze = jis.getNextEntry()) != null){
				totalFiles[0]++;
				totalSize[0] += ze.getSize();
			}
			return true;
		} catch (Exception e){ return false; }
	}
	
	public boolean unJar(File jarFile, File destDir){
		return unJar(jarFile.getPath(), destDir.getPath());
	}
	
	/** UnJar
	* @param jarFile jar file name.
	* @param destDir Director to extract the files in the jar file
	* @return true if successful
	*/
	public boolean unJar(String jarFile, String destDir){
		try {
			getJarFileInfo(jarFile, m_totalFiles, m_totalSize);
			onProgressBegin(m_totalFiles[0], m_totalSize[0]);
			FileInputStream fis = new FileInputStream(jarFile);
			JarInputStream jis = new JarInputStream(fis);
			ZipEntry ze = null;
		
			File file = new File(destDir);
			if (!destDir.endsWith(file.separator)) destDir = destDir.concat(file.separator);
			
			if (!file.exists() && !file.mkdir()){
				System.out.println("Cannot make dir."); return false;
			}
				
			FileOutputStream fos = null;
			byte[] buf = new byte[BUF_SIZE];
			int readSize = 0;
			File dir = null;
			String dirName;
			while ((ze = jis.getNextJarEntry()) != null) {
				dirName = destDir + ze.getName();

				file = new File(destDir + ze.getName());
				dirName = dirName.substring(0, dirName.length() - file.getName().length());
				dir = new File(dirName);
				if (!dir.exists() && !dir.mkdirs()){
					System.out.println("Cannot make dir.");
					return false;
				}
				
				if (ze.isDirectory()){
					System.out.println("*** DIR ***");
					// if (!file.mkdir()) return false;
				} else {
					file.createNewFile();
					onProgress(m_totalFiles[0], m_totalSize[0], ze.getSize());
					fos = new FileOutputStream(file);
					while ((readSize = jis.read(buf, 0, BUF_SIZE)) > 0)
						fos.write(buf, 0, readSize);
					fos.close();
				}
			}/** while ((ze = jis.getNextJarEntry()) != null) { */
			jis.close();
			fis.close();
			onProgressEnd(m_totalFiles[0], m_totalSize[0]);
			return true;
		} catch (Exception e){ return false; }
	}
	
	public boolean jar(File srcFile, File jarFile){
		return jar(srcFile.getPath(), jarFile.getPath());
	}
	
	/** Put one file or director to a jar file
	* @param srcFile The file or director to jar
	* @param jarFile The destination jar file
	* @return true if successful
	*/
	public boolean jar(String srcFile, String jarFile){
		JarOutputStream jos = null;
		File file = null;
		try {
			file = new File(srcFile);
			if (!file.exists() || !file.canRead()) return false;
			
			sumFileSize(srcFile, m_totalFiles, m_totalSize);
			onProgressBegin(m_totalFiles[0], m_totalSize[0]);
			
			String curPath = file.getPath().substring(0, file.getPath().length() - file.getName().length());
			jos = new JarOutputStream(new FileOutputStream(jarFile));	// overwrite
			
			jarDir(jos, curPath, srcFile);
			jos.close();
			onProgressEnd(m_totalFiles[0], m_totalSize[0]);
			return true;
		} catch (Exception e){ return false; }
	}
	
	public boolean jar(File[] srcFiles, File jarFile){
		if (srcFiles == null || srcFiles.length < 1) return false;
		String[] fileNames = new String[srcFiles.length];
		for (int i = 0; i < srcFiles.length; i++)
			fileNames[i] = srcFiles[i].getPath();
		return jar(fileNames, jarFile.getPath());
	}
	
	/** Put multi file or director to a jar file
	* @param srcFiles The files or directors to jar
	* 	the first file's directory is used for current directory
	* @param jarFile The destination jar file
	* @return true if successful
	*/
	public boolean jar(String[] srcFiles, String jarFile){
		JarOutputStream jos = null;
		File file = null;
		try {
			if (srcFiles == null || srcFiles.length < 1) return false;
			file = new File(srcFiles[0]);
			if (!file.exists() || !file.canRead()) return false;

			sumFileSize(srcFiles, m_totalFiles, m_totalSize);
			onProgressBegin(m_totalFiles[0], m_totalSize[0]);
			String curPath = file.getPath().substring(0, file.getPath().length() - file.getName().length());
			jos = new JarOutputStream(new FileOutputStream(jarFile));	// overwrite

			for (int i = 0; i < srcFiles.length; i++)
				if (!jarDir(jos, curPath, srcFiles[i])) return false;
			jos.close();
			onProgressEnd(m_totalFiles[0], m_totalSize[0]);
			return true;
		} catch (Exception e){ return false; }
	}
	
	/** Jar one directory or file
	*/
	private boolean jarDir(JarOutputStream jos, String curPath, String srcDir){
		try {
			File file = new File(srcDir);
			File[] files = file.listFiles();
			if (files == null){
				if (!file.isDirectory()) doJar(jos, curPath, file.getPath());
			} else for (int i = 0; i < files.length; i++){
				if (files[i].isDirectory() && !files[i].getName().equals(".") && !files[i].getName().equals(".."))
					jarDir(jos, curPath, files[i].getPath());
				else doJar(jos, curPath, files[i].getPath());
			}
			return true;
		} catch (Exception e){ return false; }
	}
	
	/** Do the jar job
	* compress the stream and make a jar file.
	*/
	private boolean doJar(JarOutputStream jos, String curPath, String fullFileName){
		try {
			File file = new File(fullFileName);
			if (!file.isDirectory()){	// if file is directory, don't add entry
				onProgress(m_totalFiles[0], m_totalSize[0], file.length());

				jos.putNextEntry(new ZipEntry(new String(fullFileName.substring(curPath.length()))));
				FileInputStream fis = new FileInputStream(file);
			
				// int doneSize = 0;
				int readSize = 0;
				byte[] buf = new byte[BUF_SIZE];
			
				while ((readSize = fis.read(buf, 0, BUF_SIZE)) > 0){
					jos.write(buf, 0, readSize);
					// doneSize += readSize;
				}
				fis.close(); fis = null;
			}
		
			jos.flush();
			return true;
		} catch (Exception e){ return false; }
	}
	
	private boolean doJar(JarOutputStream jos, String curPath, File file){
		return doJar(jos, curPath, file.getPath());
	}

	// public static void main(String[] args) throws Exception{
		// unJar("e:\\www.jar", "e:\\jjj");
		// jar("e:\\src", "e:\\www.jar");
		/**
		String[] srcFiles = {"d:\\work", "d:\\props.txt"};
		jar(srcFiles, "e:\\w1.jar");*/
		/**
		int[] totalFiles = {0};
		long[] totalSize = {0};
		sumFileSize("d:\\props.txt", totalFiles, totalSize);
		System.out.println(totalSize[0]);*/
	// }
	
	interface ProgressListener{
		public void JarProcessBegin(int totalFiles, long totalSize);
		public void JarProcess(int totalFiles, long totalSize, long fileSize);
		public void JarProcessEnd(int totalFiles, long totalSize);
	}	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -