您好,欢迎访问一九零五行业门户网

java如何将图片生成.tar文件

java如何将图片生成.tar文件
.tar是一种压缩格式的后缀,使用java也可以实现将文件压缩成tar格式,下面我们定义一个tarcompression(string[] filespatharray, string resultfilepath) 方法来实现这一功能。
(相关视频教程分享:java视频教程)
1、实现tarcompression(string[] filespatharray, string resultfilepath)
/* tar打包压缩 * @param filespatharray 要压缩的文件的全路径(数组) * @param resultfilepath 压缩后的文件全文件名(.tar) * @throws exception */public static boolean tarcompression(string[] filespatharray, string resultfilepath) throws exception { system.out.println(" tarcompression -> compression start!"); fileoutputstream fos = null; tararchiveoutputstream taos = null; try { fos = new fileoutputstream(new file(resultfilepath)); taos = new tararchiveoutputstream(fos); for (string filepath : filespatharray) { bufferedinputstream bis = null; fileinputstream fis = null; try { file file = new file(filepath); tararchiveentry tae = new tararchiveentry(file); // 此处指明 每一个被压缩文件的名字,以便于解压时tararchiveentry的getname()方法获取到的直接就是这里指定的文件名 // 以(左边的)gbk编码将file.getname()“打碎”为序列,再“组装”序列为(右边的)gbk编码的字符串 tae.setname(new string(file.getname().getbytes("gbk"), "gbk")); taos.putarchiveentry(tae); fis = new fileinputstream(file); bis = new bufferedinputstream(fis); int count; byte data[] = new byte[1024]; while ((count = bis.read(data, 0, 1024)) != -1) { taos.write(data, 0, count); } } finally { taos.closearchiveentry(); if (bis != null) bis.close(); if (fis != null) fis.close(); } } } finally { if (taos != null) taos.close(); if (fos != null) fos.close(); } system.out.println(" tarcompression -> compression end!"); return true;}
2、使用定义的tarcompression方法将图片压缩生成.tar文件。
public static void main(string[] args) { tarcompression(new string["a.png", "b.png"], "e:\test.tar")}
,大量免费编程学习课程,欢迎学习。
以上就是java如何将图片生成.tar文件的详细内容。
其它类似信息

推荐信息