当前位置 : 主页 > 编程语言 > java >

java解压tar文件

来源:互联网 收集:自由互联 发布时间:2021-06-28
解压tar文件,并重命名,针对javatar.jar包等不能解压包含gzip,bz2属性的文件 import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;public class T {public s
解压tar文件,并重命名,针对javatar.jar包等不能解压包含gzip,bz2属性的文件
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class T {

	public static void main(String[] args) throws Exception {
		extTarFileList("/home/hadoop/Desktop/bzip2.tar", "/home/hadoop/Desktop/");
	}

	private static void extTarFileList(String filename, String directory) {
		File file = new File(filename);
		String outPath = directory + file.getName().substring(0, file.getName().length() - 4) + new Date().getTime()
				+ "/";
		File dir = new File(outPath);

		dir.mkdir();

		String tarmd = "tar -xf  " + filename + " -C " + outPath;
		String[] cmds = { "/bin/sh", "-c", tarmd };
		Process pro = null;
		try {
			pro = Runtime.getRuntime().exec(cmds);
			pro.waitFor();
			List
 
   files = getFiles(outPath);
			for (File f : files) {
				renameFile(f);
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (InterruptedException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			pro.destroy();
		}

	}

	/**
	 * 文件重命名
	 *
	 * @param path
	 *            文件目录
	 * @param oldname
	 *            原来的文件名
	 * @param newname
	 *            新文件名
	 * @return
	 */
	public static File renameFile(File oldfile) {

		File newfile = new File(oldfile.getParent() + "/" + new Date().getTime() + "-" + oldfile.getName());
		if (!oldfile.exists()) {
			return null;// 重命名文件不存在
		}
		oldfile.renameTo(newfile);
		return newfile;
	}

	/***
	 * 指定文件夹下的所有文件
	 * 
	 * @param path
	 * @return
	 */
	public static List
  
    getFiles(String path) { File root = new File(path); List
   
     files = new ArrayList
    
     (); if (!root.isDirectory()) { files.add(root); } else { File[] subFiles = root.listFiles(); for (File f : subFiles) { files.addAll(getFiles(f.getAbsolutePath())); } } return files; } }
    
   
  
 
上一篇:JAVA excel模板导出
下一篇:Maven发布项目
网友评论