java通过ant、compress压缩文件并添加可执行权限的多种方法

背景

某次软件发布后客户发现iOS的软件包无法暗转缺少可执行权限, 同事分析后发现是压缩过程中文件可执行权限丢失. 于是在网上搜索了一些保留执行权限的方法

解决办法

方法一. 通过ant权限压缩并赋予0755权限

ant对应pom.xml 如下


<dependency>
    <groupId>org.apache.antgroupId>
    <artifactId>antartifactId>
    <version>1.10.13version>
dependency>

ant 代码如下:

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
	public static void write(File path, File zipFile) throws IOException {
		ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
		zip.setEncoding("GBK");
		Util.write(path, path, zip);
		zip.close();
	}
 
	private static void write(File base, File path, ZipOutputStream zip) throws IOException {
		URI rel = base.toURI().relativize(path.toURI());
		if (path.isDirectory()) {
			ZipEntry entry = new ZipEntry(rel.getPath());
			entry.setUnixMode(0755);
			zip.putNextEntry(entry);
			zip.closeEntry();
			File[] files = path.listFiles();
			for (File file : files) {
				write(base, file, zip);
			}
		} else {
			ZipEntry entry = new ZipEntry(rel.getPath());
			entry.setUnixMode(644);
			zip.putNextEntry(entry);
			FileInputStream is = new FileInputStream(path);
			zip.write(IOUtils.toByteArray(is));
			is.close();
			zip.closeEntry();
		}
	}

方法二. 通过compress进行压缩,并授权0755

java代码如下:

public class JdCompressUtil {
 
    public static void toZipWithoutDir(String srcDir, String targetFile)
            throws RuntimeException, FileNotFoundException {
 
        OutputStream out = new FileOutputStream(targetFile);
 
        File sourceFile = new File(srcDir);
 
        List<File> files = Arrays.asList(sourceFile.listFiles());
 
        files = files.stream().filter(file -> file.isFile()).collect(Collectors.toList());
 
        toZip(files, out);
    }
 
    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipArchiveOutputStream zos = null;
        try {
            zos = new ZipArchiveOutputStream(out);
            for (File srcFile : srcFiles) {
 
                ZipArchiveEntry entry = new ZipArchiveEntry(srcFile.getName());
 
                entry.setUnixMode(0755);
 
                zos.putArchiveEntry(entry);
 
                FileInputStream in = new FileInputStream(srcFile);
 
                BufferedInputStream ins = new BufferedInputStream(new FileInputStream(srcFile.getAbsolutePath()));
                IOUtils.copy(ins, zos);
 
                zos.closeArchiveEntry();
 
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

方法三. 通过jarchivelib解压缩

jarchivelib对应pom.xml 如下


<dependency>
    <groupId>org.rauschiggroupId>
    <artifactId>jarchivelibartifactId>
    <version>1.2.0version>
dependency>

解压缩java 代码如下:

import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;

  public static void unzip(File zipFile, File targetDirectory) throws IOException, IllegalAccessException {
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP);
    archiver.extract(zipFile, targetDirectory);
  }

  public static void unTarGz(File tarFile, File targetDirectory) throws IOException {
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
    archiver.extract(tarFile, targetDirectory);
  }

方法四. 通过执行linux命令修改权限

chmod 755

private void execShell(String scriptPath, String... para) {
        try {
 
            String[] cmd = new String[]{scriptPath};
 
            //为了解决参数中包含空格
            cmd = ArrayUtils.addAll(cmd, para);
 
            //解决脚本没有执行权限
            ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "755", scriptPath);
            Process process = builder.start();
            process.waitFor();
            Process ps = Runtime.getRuntime().exec(cmd);
            ps.waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            //执行结果
            String result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

方法五. 通过PosixFilePermission 修改权限

public static void chmod755(File file ) throws IllegalStateException {
 
        //设置权限
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ); //设置所有者的读取权限
        perms.add(PosixFilePermission.OWNER_WRITE); //设置所有者的写权限
        perms.add(PosixFilePermission.OWNER_EXECUTE); //设置所有者的执行权限
        perms.add(PosixFilePermission.GROUP_READ); //设置组的读取权限
        perms.add(PosixFilePermission.GROUP_EXECUTE); //设置组的读取权限
        perms.add(PosixFilePermission.OTHERS_READ); //设置其他的读取权限
        perms.add(PosixFilePermission.OTHERS_EXECUTE); //设置其他的读取权限
        try {
            //设置文件和文件夹的权限
            Path pathParent = Paths.get(file.getParentFile().getAbsolutePath());
            Path pathDest = Paths.get(file.getAbsolutePath());
            Files.setPosixFilePermissions(pathParent, perms);   //修改文件夹路径的权限
            Files.setPosixFilePermissions(pathDest, perms);  //修改图片文件的权限
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

方法六. 通过File直接修改权限

File file = new File(path)
 
file.setExecutable(true);
file.setReadable(true);
file.setWritable(true);

参考

  1. java代码ant、compress压缩文件,并保留文件的可执行权限
  2. 通过java代码更改文件权限
  3. Maintain file permissions when extracting from a zip file using JDK 5 api
  4. https://github.com/apache/ant/blob/rel/1.10.9/src/main/org/apache/tools/ant/util/PermissionUtils.java

你可能感兴趣的:(Java,java,开发语言,7-zip,压缩,文件操作,ZipEntry)