Discuss / Java / 做了个打包压缩的小工具,通过递归方法获取相对路径

做了个打包压缩的小工具,通过递归方法获取相对路径

Topic source

Best of Me

#1 Created at ... [Delete] [Delete and Lock User]
public class ZipTest {



	public static void main(String[] args) throws IOException {

		// TODO Auto-generated method stub

		File source = new File("D:\\Java\\demo");

		File target = new File("D:\\Java\\demo.zip");

		toZip(source, target);

		Desktop.getDesktop().open(target);



	}



	public static void toZip(File source, File target) throws IOException {

		try (ZipOutputStream outPut = new ZipOutputStream(new FileOutputStream(target))) {

			File[] files = source.listFiles();

			for (File file : files) {

				zipTools(file, source, outPut);

				outPut.closeEntry();

			}

			System.out.println(target + "打包结束!");

		}

	}



	// 递归函数

	public static void zipTools(File file, File source, ZipOutputStream outPut) throws IOException {

		if (file.isFile()) {

			outPut.putNextEntry(new ZipEntry(getRelativePath(file, source)));

			outPut.write(Files.readAllBytes(file.toPath()));

		} else {

			outPut.putNextEntry(new ZipEntry(getRelativePath(file, source) + File.separator));

			for (File subFile : file.listFiles()) {

				file = subFile;

				zipTools(subFile, source, outPut);

			}

		}

	}



//获得相对路径

	public static String getRelativePath(File childFile, File parentFile) {

		return childFile.getPath().substring(parentFile.getPath().length() + 1);

	}

}


  • 1

Reply