国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase Solution to decompression garbled code in java

Solution to decompression garbled code in java

Nov 26, 2019 am 10:39 AM
java

Solution to decompression garbled code in java

第一種使用ant實現(xiàn)的zip解壓縮,其中解壓的亂碼注意使用

public void unZip(String unZipFileName,String outputPath) 其中

this.zipFile = new ZipFile(unZipFileName, "GB18030");是解決中文名亂碼的關(guān)鍵。

import java.io.*;
import org.apache.tools.zip.*;
import java.util.Enumeration;
 
/**
 *<p>
 * <b>功能:zip壓縮、解壓(支持中文文件名)</b>
 *<p>
 * 說明:使用Apache Ant提供的zip工具org.apache.tools.zip實現(xiàn)zip壓縮和解壓功能.
 * 解決了由于java.util.zip包不支持漢字的問題。
 * 
 * @author Winty
 * @modifier vernon.zheng
 */
public class AntZip {
	private ZipFile zipFile;
	private ZipOutputStream zipOut; // 壓縮Zip
	private ZipEntry zipEntry;
	private static int bufSize; // size of bytes
	private byte[] buf;
	private int readedBytes;
	// 用于壓縮中。要去除的絕對父路路徑,目的是將絕對路徑變成相對路徑。
	private String deleteAbsoluteParent;
 
	/**
	 *構(gòu)造方法。默認緩沖區(qū)大小為512字節(jié)。
	 */
	public AntZip() {
		this(512);
	}
 
	/**
	 *構(gòu)造方法。
	 * 
	 * @param bufSize
	 *            指定壓縮或解壓時的緩沖區(qū)大小
	 */
	public AntZip(int bufSize) {
		this.bufSize = bufSize;
		this.buf = new byte[this.bufSize];
		deleteAbsoluteParent = null;
	}
 
	/**
	 *壓縮文件夾內(nèi)的所有文件和目錄。
	 * 
	 * @param zipDirectory
	 *            需要壓縮的文件夾名
	 */
	public void doZip(String zipDirectory) {
		File zipDir = new File(zipDirectory);
		doZip(new File[] { zipDir }, zipDir.getName());
	}
 
	/**
	 *壓縮多個文件或目錄??梢灾付ǘ鄠€單獨的文件或目錄。而 <code>doZip(String zipDirectory)</code>
	 * 則直接壓縮整個文件夾。
	 * 
	 * @param files
	 *            要壓縮的文件或目錄組成的<code>File</code>數(shù)組。
	 *@param zipFileName
	 *            壓縮后的zip文件名,如果后綴不是".zip", 自動添加后綴".zip"。
	 */
	public void doZip(File[] files, String zipFileName) {
		// 未指定壓縮文件名,默認為"ZipFile"
		if (zipFileName == null || zipFileName.equals(""))
			zipFileName = "ZipFile";
 
		// 添加".zip"后綴
		if (!zipFileName.endsWith(".zip"))
			zipFileName += ".zip";
 
		try {
			this.zipOut = new ZipOutputStream(new BufferedOutputStream(
					new FileOutputStream(zipFileName)));
			compressFiles(files, this.zipOut, true);
			this.zipOut.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
 
	/**
	 *壓縮文件和目錄。由doZip()調(diào)用
	 * 
	 * @param files
	 *            要壓縮的文件
	 *@param zipOut
	 *            zip輸出流
	 *@param isAbsolute
	 *            是否是要去除的絕對路徑的根路徑。因為compressFiles()
	 *            會遞歸地被調(diào)用,所以只用deleteAbsoluteParent不行。必須用isAbsolute來指明
	 *            compressFiles()是第一次調(diào)用,而不是后續(xù)的遞歸調(diào)用。即如果要壓縮的路徑是
	 *            E:\temp,那么第一次調(diào)用時,isAbsolute=true,則deleteAbsoluteParent會記錄
	 *            要刪除的路徑就是E:\ ,當(dāng)壓縮子目錄E:\temp\folder時,isAbsolute=false,
	 *            再遞歸調(diào)用compressFiles()時,deleteAbsoluteParent仍然是E:\ 。從而保證了
	 *            將E:\temp及其子目錄均正確地轉(zhuǎn)化為相對目錄。這樣壓縮才不會出錯。不然絕對 路徑E:\也會被寫入到壓縮文件中去。
	 */
	private void compressFiles(File[] files, ZipOutputStream zipOut,
			boolean isAbsolute) throws IOException {
 
		for (File file : files) {
			if (file == null)
				continue; // 空的文件對象
 
			// 刪除絕對父路徑
			if (file.isAbsolute()) {
				if (isAbsolute) {
					deleteAbsoluteParent = file.getParentFile()
							.getAbsolutePath();
					deleteAbsoluteParent = appendSeparator(deleteAbsoluteParent);
				}
			} else
				deleteAbsoluteParent = "";
 
			if (file.isDirectory()) {// 是目錄
				compressFolder(file, zipOut);
			} else {// 是文件
				compressFile(file, zipOut);
			}
		}
	}
 
	/**
	 *壓縮文件或空目錄。由compressFiles()調(diào)用。
	 * 
	 * @param file
	 *            需要壓縮的文件
	 *@param zipOut
	 *            zip輸出流
	 */
	public void compressFile(File file, ZipOutputStream zipOut)
			throws IOException {
 
		String fileName = file.toString();
 
		/* 去除絕對父路徑。 */
		if (file.isAbsolute())
			fileName = fileName.substring(deleteAbsoluteParent.length());
		if (fileName == null || fileName == "")
			return;
 
		/*
		 * 因為是空目錄,所以要在結(jié)尾加一個"/"。 不然就會被當(dāng)作是空文件。 ZipEntry的isDirectory()方法中,目錄以"/"結(jié)尾.
		 * org.apache.tools.zip.ZipEntry : public boolean isDirectory() { return
		 * getName().endsWith("/"); }
		 */
		if (file.isDirectory())
			fileName = fileName + "/";// 此處不能用"\\"
 
		zipOut.putNextEntry(new ZipEntry(fileName));
 
		// 如果是文件則需讀;如果是空目錄則無需讀,直接轉(zhuǎn)到zipOut.closeEntry()。
		if (file.isFile()) {
			FileInputStream fileIn = new FileInputStream(file);
			while ((this.readedBytes = fileIn.read(this.buf)) > 0) {
				zipOut.write(this.buf, 0, this.readedBytes);
			}
			fileIn.close();
		}
 
		zipOut.closeEntry();
	}
 
	/**
	 *遞歸完成目錄文件讀取。由compressFiles()調(diào)用。
	 * 
	 * @param dir
	 *            需要處理的文件對象
	 *@param zipOut
	 *            zip輸出流
	 */
	private void compressFolder(File dir, ZipOutputStream zipOut)
			throws IOException {
 
		File[] files = dir.listFiles();
 
		if (files.length == 0)// 如果目錄為空,則單獨壓縮空目錄。
			compressFile(dir, zipOut);
		else
			// 如果目錄不為空,則分別處理目錄和文件.
			compressFiles(files, zipOut, false);
	}
 
	/**
	 *解壓指定zip文件。
	 * 
	 * @param unZipFileName
	 *            需要解壓的zip文件名
	 */
	public void unZip(String unZipFileName) {
		FileOutputStream fileOut;
		File file;
		InputStream inputStream;
 
		try {
			this.zipFile = new ZipFile(unZipFileName);
 
			for (Enumeration entries = this.zipFile.getEntries(); entries
					.hasMoreElements();) {
 
				ZipEntry entry = (ZipEntry) entries.nextElement();
				file = new File(entry.getName());
 
				if (entry.isDirectory()) {// 是目錄,則創(chuàng)建之
					file.mkdirs();
				} else {// 是文件
					// 如果指定文件的父目錄不存在,則創(chuàng)建之.
					File parent = file.getParentFile();
					if (parent != null && !parent.exists()) {
						parent.mkdirs();
					}
 
					inputStream = zipFile.getInputStream(entry);
 
					fileOut = new FileOutputStream(file);
					while ((this.readedBytes = inputStream.read(this.buf)) > 0) {
						fileOut.write(this.buf, 0, this.readedBytes);
					}
					fileOut.close();
 
					inputStream.close();
				}
			}
			this.zipFile.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	/**
	 *解壓指定zip文件。其中"GB18030"解決中文亂碼
	 * 
	 * @param unZipFileName
	 *            需要解壓的zip文件名
	 * @param outputPath
	 *            輸出路徑
	 */
	public void unZip(String unZipFileName,String outputPath) {
		FileOutputStream fileOut;
		File file;
		InputStream inputStream;
 
		try {
			this.zipFile = new ZipFile(unZipFileName, "GB18030");
 
			for (Enumeration entries = this.zipFile.getEntries(); entries
					.hasMoreElements();) {
 
				ZipEntry entry = (ZipEntry) entries.nextElement();
				file = new File(outputPath+entry.getName());
 
				if (entry.isDirectory()) {// 是目錄,則創(chuàng)建之
					file.mkdirs();
				} else {// 是文件
					// 如果指定文件的父目錄不存在,則創(chuàng)建之.
					File parent = file.getParentFile();
					if (parent != null && !parent.exists()) {
						parent.mkdirs();
					}
 
					inputStream = zipFile.getInputStream(entry);
 
					fileOut = new FileOutputStream(file);
					while ((this.readedBytes = inputStream.read(this.buf)) > 0) {
						fileOut.write(this.buf, 0, this.readedBytes);
					}
					fileOut.close();
 
					inputStream.close();
				}
			}
			this.zipFile.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
 
	/**
	 *給文件路徑或目錄結(jié)尾添加File.separator
	 * 
	 * @param fileName
	 *            需要添加路徑分割符的路徑
	 *@return 如果路徑已經(jīng)有分割符,則原樣返回,否則添加分割符后返回。
	 */
	private String appendSeparator(String path) {
		if (!path.endsWith(File.separator))
			path += File.separator;
		return path;
	}
 
	/**
	 *解壓指定zip文件。
	 * 
	 * @param unZipFile
	 *            需要解壓的zip文件對象
	 */
	public void unZip(File unZipFile) {
		unZip(unZipFile.toString());
	}
 
	/**
	 *設(shè)置壓縮或解壓時緩沖區(qū)大小。
	 * 
	 * @param bufSize
	 *            緩沖區(qū)大小
	 */
	public void setBufSize(int bufSize) {
		this.bufSize = bufSize;
	}
	// 主函數(shù),用于測試AntZip類
	/*
	 * public static void main(String[] args)throws Exception{
	 * if(args.length>=2){ AntZip zip = new AntZip();
	 * 
	 * if(args[0].equals("-zip")){ //將后續(xù)參數(shù)全部轉(zhuǎn)化為File對象 File[] files = new File[
	 * args.length - 1]; for(int i = 0;i < args.length - 1; i++){ files = new
	 * File(args[i + 1]); }
	 * 
	 * //將第一個文件名作為zip文件名 zip.doZip(files , files[0].getName());
	 * 
	 * return ; } else if(args[0].equals("-unzip")){ zip.unZip(args[1]); return
	 * ; } }
	 * 
	 * System.out.println("Usage:");
	 * System.out.println("壓縮:java AntZip -zip [directoryName | fileName]... ");
	 * System.out.println("解壓:java AntZip -unzip fileName.zip"); }
	 */
 
}

第二種 從修改ZipInputStream及ZipOutputStream對於檔名的編碼方式來著手了。

我們可以從jdk的src.zip取得ZipInputStream及ZipOutputStream的原始碼來加以修改:

一、ZipOutputStream.java

1.從jdk的src.zip取得ZipOutputStream.java原始碼,另存新檔存到c:/java/util/zip這個資料夾里,檔名改為CZipOutputStream.java。

2.開始修改原始碼,將class名稱改為CZipOutputStream

3.建構(gòu)式也必須更改為CZipOutputStream

4.新增member,這個member記錄編碼方式

private String encoding="UTF-8";

5.再新增一個建構(gòu)式(這個建構(gòu)式可以讓這個class在new的時候,設(shè)定檔名的編碼)

 public CZipOutputStream(OutputStream out,String encoding) { 
     super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); 
     usesDefaultDeflater = true; 
     this.encoding=encoding; 
  }

推薦:java基礎(chǔ)教程

The above is the detailed content of Solution to decompression garbled code in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles