java notes - file compression

First, the listFile() method returns the full path of all files and subdirectories under the directory indicated by the File object, and the return value is the File [] array.

The list() method returns the filename (not the full path)

Example:

import java.io.File;

public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file = new File("F:/myword");
		File f[]=file.listFiles(); //Get File path array
		for(int i=0;i<f.length;i++){
			System.out.println(f[i]);
		}
	}

}

Operation result:

 

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 MyZip {
public void zip(String zipFilename, File inputFile) throws IOException{  
	
	ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));
	zip(out,inputFile,"");  //Call compression method
	System.out.println("Compression...");
	out.close();            //Closed flow	
}
//Compression method
public void zip(ZipOutputStream out,File f,String base) throws IOException{  
		if(f.isDirectory()){          //If the file represented by the f object is a directory
			File[] fl =f.listFiles(); //Call listFile() method to get all paths
			if(base.length()!=0){
				out.putNextEntry(new ZipEntry(base+"/"));
			}
			for(int i=0;i<fl.length;i++){
				zip(out,fl[i],base+fl[i]);
			}
		}else{
			out.putNextEntry(new ZipEntry(base)); //Create a new entry point
			FileInputStream in = new FileInputStream(f);
			int b;
			System.out.println(base);
			while((b=in.read())!=-1){  //If the tail of the flow is not reached
				out.write(b);         //Write bytes to the current Zip entry
			}
			in.close();
		}
	}

}

There is a bug in the compressed code of this file, which will generate some inexplicable files, but the time is pressing. I have to continue to learn. If a good God accidentally passes by, I hope you will give me some advice. Thank you very much! Huai Quan!

Keywords: Java

Added by whansen02 on Thu, 02 Jan 2020 21:01:57 +0200