1.解压文件到指定目录

/**
* 解压文件到指定目录
* zipFile:要解压的文件
* descDir:解压到哪个文件
*
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile,String descDir)throws IOException
{
File pathFile = new File(descDir);
if(!pathFile.exists())
{
pathFile.mkdirs();
}
//解决zip文件中有中文目录或者中文文件
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for(Enumeration entries = zip.entries(); entries.hasMoreElements();)
{
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists())
{
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory())
{
continue;
}
//输出文件路径信息
System.out.println(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0)
{
out.write(buf1,0,len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
}

解压tar.gz 文件

package com.hou;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream; import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream; /**
* 解压tar.gz 文件
* ClassName: Test01
* @Description: TODO
* @author HJJ
* @date 2018年10月17日
*/
public class Test01 { public static void main(String[] args) {
File file=new File("D:/home/app/data/tiantai/new/pred_2018-10-15.tar.gz");
String str="D:/home/app/data/tiantai/new/";
try {
unTarGz(file,str);
System.out.println("解压成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //------------------------------------------------------------------------------------------------------
/**
* 解压tar.gz 文件
* @param file 要解压的tar.gz文件对象
* @param outputDir 要解压到某个指定的目录下
* @throws IOException
*/
public static void unTarGz(File file,String outputDir) throws IOException{
TarInputStream tarIn = null;
try{
tarIn = new TarInputStream(new GZIPInputStream(
new BufferedInputStream(new FileInputStream(file))),
1024 * 2); createDirectory(outputDir,null);//创建输出目录 TarEntry entry = null;
while( (entry = tarIn.getNextEntry()) != null ){ if(entry.isDirectory()){//是目录
entry.getName();
createDirectory(outputDir,entry.getName());//创建空目录
}else{//是文件
File tmpFile = new File(outputDir + "/" + entry.getName());
createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
OutputStream out = null;
try{
out = new FileOutputStream(tmpFile);
int length = 0; byte[] b = new byte[2048]; while((length = tarIn.read(b)) != -1){
out.write(b, 0, length);
} }catch(IOException ex){
throw ex;
}finally{ if(out!=null)
out.close();
}
}
}
}catch(IOException ex){
throw new IOException("解压归档文件出现异常",ex);
} finally{
try{
if(tarIn != null){
tarIn.close();
}
}catch(IOException ex){
throw new IOException("关闭tarFile出现异常",ex);
}
}
} /**
* 构建目录
* @param outputDir
* @param subDir
*/
public static void createDirectory(String outputDir,String subDir){
File file = new File(outputDir);
if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
file = new File(outputDir + "/" + subDir);
}
if(!file.exists()){
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
file.mkdirs();
}
} }

3.解压指定目录下的zip文件

/**
* 解压指定目录下的zip文件
* @param checkPath 检测目录,先从缓存中取,如果缓存中不存在,再从配置文件中提取
* @param fileName 待解压的zip文件
* @throws Exception
*/
private static void unzip(String checkPath,String fileName) throws Exception { if (checkPath.startsWith("~")) {
checkPath = System.getProperty("user.home")+ checkPath.substring(1);
} // final String currentPath = checkPath;
final String currentPath = "D:/home/app/data/tiantai/new/"; // String fileRoot = checkPath + File.separator + fileName; //zip文件路径
String fileRoot = "D:/home/app/data/tiantai/new/QUNAR_ONE_COMMON_PRYPAY_1539141468602.zip"; //zip文件路径
//System.out.println("解压的zip文件 fileRoot:" + fileRoot);
System.out.println("解压的zip文件 fileRoot:" + fileRoot); FileSystem fs = FileSystems.newFileSystem(Paths.get(fileRoot),null); Files.walkFileTree(fs.getPath("/"),new SimpleFileVisitor<Path>(){ //遍历文件系统时,可获取文件属性
/**
* Invoked for a file in a directory.
* <p>
* <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE
* CONTINUE}.
*
* @param file
* @param attrs
*/
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path destPath = Paths.get(currentPath,file.toString());
Files.deleteIfExists(destPath);//如果目标文件已经存在,则删除
Files.createDirectories(destPath.getParent());//创建文件的父目录,不管是文件还是目录
Files.move(file, destPath); return FileVisitResult.CONTINUE;
}
}); fs.close();//关闭文件系统 //文件解压成功后,删除zip文件
File delZipFile = new File(fileRoot);
if(delZipFile.exists() && delZipFile.isFile()){
boolean d = delZipFile.delete();
if(d){
// System.out.println(fileRoot + " 文件已删除...");
System.out.println((fileRoot + " 文件已删除...")); } } }

4.

public static void Decompressing2() throws IOException {
// String path = "D:/home/app/data/tiantai/new/";
String path = "D:/home/app/data/tiantai/new/";
ZipEntry zipEntry = null;
try {
// ZipInputStream读取压缩文件
FileInputStream file=new FileInputStream(new File(path+"QUNAR_ONE_COMMON_PRYPAY_1539679543536.zip"));
// ZipFile zipFile = new ZipFile(new File(path+"QUNAR_ONE_COMMON_PRYPAY_1539141468602.zip"),Charset.forName("gbk")) ;
ZipInputStream zipInputStream = new ZipInputStream(file);
// 写入到缓冲流中
BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);
File fileOut = null;
// 读取压缩文件中的一个文件
// zipEntry = zipInputStream.getNextEntry();
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
// 若当前zipEntry是一个文件夹
if (zipEntry.isDirectory()) {
fileOut = new File(path + "//" +zipEntry.getName());
// 在指定路径下创建文件夹
if (!fileOut.exists()) {
fileOut.mkdirs();
}
//若是文件
} else {
// 原文件名与指定路径创建File对象(解压后文件的对象)
fileOut = new File(path, zipEntry.getName());
try(
FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);){
//将文件写入到指定file中
int b = 0;
while ((b = bufferedInputStream.read()) != -1) {
bufferedOutputStream.write(b);
}
}catch (Exception e) {
e.printStackTrace();
}
} } } catch (Exception e) {
e.printStackTrace();
}
}

5

readByZipInputStream("D:/home/app/data/tiantai/new/QUNAR_ONE_COMMON_PRYPAY_1539065367654.zip", "d:/");

public static void readByZipInputStream(String archive, String decompressDir)
throws FileNotFoundException, IOException {
BufferedInputStream bi; ZipFile zf = new ZipFile(archive, Charset.forName("gbk"));//支持中文 Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry) e.nextElement();
String entryName = ze2.getName();
String path = decompressDir + "/" + entryName;
if (ze2.isDirectory()) {
System.out.println("正在创建解压目录 - " + entryName);
File decompressDirFile = new File(path);
if (!decompressDirFile.exists()) {
decompressDirFile.mkdirs();
}
} else {
System.out.println("正在创建解压文件 - " + entryName);
String fileDir = path.substring(0, path.lastIndexOf("/"));
File fileDirFile = new File(fileDir);
if (!fileDirFile.exists()) {
fileDirFile.mkdirs();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(
decompressDir + "/" + entryName)); bi = new BufferedInputStream(zf.getInputStream(ze2));
byte[] readContent = new byte[1024];
int readCount = bi.read(readContent);
while (readCount != -1) {
bos.write(readContent, 0, readCount);
readCount = bi.read(readContent);
}
bos.close();
}
}
zf.close();
}

6.修改文件名

/**
* 通过文件路径直接修改文件名
* @param filePath 需要修改的文件的完整路径
* @param newFileName 需要修改的文件的名称
* @return
*/
public static String FixFileName(String filePath, String newFileName) {
File f = new File(filePath);
if (!f.exists()) { // 判断原文件是否存在
return null;
} newFileName = newFileName.trim();
if ("".equals(newFileName) || newFileName == null) // 文件名不能为空
return null; String newFilePath = null;
if (f.isDirectory()) { // 判断是否为文件夹
newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
} else {
newFilePath = filePath.substring(0, filePath.lastIndexOf("/"))+ "/" + newFileName ;
}
File nf = new File(newFilePath);
if (!f.exists()) { // 判断需要修改为的文件是否存在(防止文件名冲突)
return null;
} try {
f.renameTo(nf); // 修改文件名
} catch(Exception err) {
err.printStackTrace();
return null;
} return newFilePath;
}

解压.zip,.tar.gz文件到指定目录,重命名文件的更多相关文章

  1. linux中解压.tgz, .tar.gz ,zip ,gz, .tar文件

    转载:https://blog.csdn.net/fu6543210/article/details/7984578 将.tgz文件解压在当前目录: tar zxvf MY_NAME.tgz 将.ta ...

  2. zz 如何在Linux下创建与解压zip, tar, tar.gz和tar.bz2文件

    January 2nd, 2009 at 10:31 pm Linux 解压, Linux, tar, tar.bz2, tar.gz, tgz, zip, 压缩, 打包, 文档 这么多年来,数据压缩 ...

  3. 如何在Linux下创建与解压zip, tar, tar.gz和tar.bz2文件

    这么多年来,数据压缩对我们来说是非常有用的.无论是在邮件中发送的图片用的zip文件还是在服务器压缩数据文件,我们都可以让下载更容易或者有效的节约磁盘空间.某些压缩格式有时允许我们以60%的比率(甚至更 ...

  4. tar命令解压jdk.tar.gz包 报错 gzip: stdin: not in gzip format

    转自:https://blog.csdn.net/LL_zhuo/article/details/44173355 遇到和这篇博文一样的问题了.用wget 从oracle官网下载jdk, http:/ ...

  5. linux下tar gz bz2 tgz z等众多压缩文件的压缩与解压方法

    Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通常都是以.tar结尾的.生成tar包后,就可以用其它的程序来进 行压缩了,所以首先就来讲讲ta ...

  6. java解压缩.gz .zip .tar.gz等格式的压缩包方法总结

    1..gz文件是linux下常见的压缩格式.使用 java.util.zip.GZIPInputStream即可,压缩是 java.util.zip.GZIPOutputStream public s ...

  7. winform复制文件到指定目录

    执行步骤 弹出选择对话框:var openFileDialog = new OpenFileDialog(); 设置选择内容,如所有图片:openFileDialog.Filter="图像文 ...

  8. Perl复制、移动、重命名文件/目录

    File::Copy复制文件 File::Copy模块提供了copy函数和cp函数来复制文件,它们参数上完全一致,但行为上稍有区别. 用法大致如下: use File::Copy qw(copy cp ...

  9. 怎样用bat批量重命名文件夹和文件

    很早以前本人写过重命名文件夹的文章,发现其中稍有不完善的地方,其主要功能在文件夹名前统一加上字符,或者在文件夹名后统一加上字符,有网友反应功能太单一.今天我又仔细研究了一下bat批处理代码,分别能完全 ...

随机推荐

  1. 用Recover来实现更健壮的go程序

    缘起:线上的go service 挂了,无法启动. 原因:采用的第三方库有个bug, 在go携程里面执行task的时候会产生out of range 的panic, 而我又把任务队列每次加载的时候重做 ...

  2. Ubuntu 常见错误--Could not get lock

    问题产生的原因:另外一个程序正在运行,导致资源被锁不可用.而导致资源被锁的原因可能是上次运行安装或更新时没有正常完成,进而出现此状况 解决问题的办法:sudo rm /var/cache/apt/ar ...

  3. 一种SPA(单页面应用)架构

    (如果对SPA概念不清楚的同学可以先自行了解相关概念) 平时喜欢做点小页面来玩玩,并且一直采用单页面应用(Single Page Application)的方式来进行开发.这种开发方式是在之前一年做的 ...

  4. Java栈之顺序栈存储结构实现

    一.栈的基本定义 栈是一种数据结构,它代表一种特殊的线性表,这种线性表只能在固定一端(通常认为是线性表的尾端)进行插入.删除操作的特殊线性表,通常就是在线性表的尾端进行插入.删除操作. 二.顺序栈的实 ...

  5. CCTV-2《遇见大咖》专访雷军----笔记记录

    与央视记者约好两点采访,但因为公司会议拖到了三点.雷军对此表示抱歉,解释了一天的行程,并说:“今天不算密的,密的平均一天应该有十一个会.然后我现在基本每天中午饭,大概就是三分钟的时间.” 因为要上镜, ...

  6. windows安装redis, php5.5

    全套安装包地址 http://download.csdn.net/detail/whellote/9572797   解压 redis-2.2.5-win32-win64, 将里面的内容拷贝到j:/r ...

  7. Python之路——线程池

    1 线程基础 1.1 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2 线程同步——锁 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样,其实Python中是伪多线程).但是当线程 ...

  8. 【转】Winform Socket通信

    Socket相关概念[端口] 在Internet上有很多这样的主机,这些主机一般运行了多个服务软件,同时提供几种服务.每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务(应 ...

  9. NIO 03

    1. 客户端要主动去连接:channel.connect(new InetSocketAddress("localhost",8888)); //用channel.finishCo ...

  10. NIO 02 (转)

    本文转自:http://weixiaolu.iteye.com/blog/1479656 SelectionKey.OP_ACCEPT // 服务端监听,并注册OP_ACCEPT事件后,就已准备好接受 ...