常用文件操作

package com.cms21.mobilecrm.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class FileOperateUtils {
public static File dirFrom;
public static File dirTo;


// 目标路径创建文件夹
public static void listFileInDir(File file) {
File[] files = file.listFiles();
for (File f : files) {
String tempfrom = f.getAbsolutePath();
String tempto = tempfrom.replace(dirFrom.getAbsolutePath(), dirTo
.getAbsolutePath()); // 后面的路径 替换前面的路径名
if (f.isDirectory()) {
File tempFile = new File(tempto);
tempFile.mkdirs();
listFileInDir(f);
} else {
int endindex = tempto.lastIndexOf("\\");// 找到"/"所在的位置
String mkdirPath = tempto.substring(0, endindex);
File tempFile = new File(mkdirPath);
tempFile.mkdirs();// 创建立文件夹
copy(tempfrom, tempto);
}
}
}


/**
* 封装好的文件拷贝方法
*/
public static void copy(String from, String to) {
try {
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);


byte[] buff = new byte[1024];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


public static void beginCopy(String from, String to) {
File fromfile = new File(from);// 源文件夹
File tofile = new File(to);// 目标
// 设置来源去向
dirFrom = fromfile;
dirTo = tofile;
listFileInDir(fromfile);
}



// 删除某一目录下的文件及文件夹
public static void delAll(File file) {
// 是目录,则递归
File[] list = file.listFiles();
if (list.length == 0)
return;
else
for (int i = 0; i < list.length; i++) {
// System.out.println(list[i]);
if (list[i].isDirectory())
deleteDirectFiles(list[i]);
else
list[i].delete();
}
}


// 删除非空文件夹
public static void deleteDirectFiles(File file) {
File[] list = file.listFiles();
if (list.length == 0)// 文件夹为空目录
file.delete();
else {
for (int i = 0; i < list.length; i++)
if (!list[i].isDirectory())// 为文件时直接删除
list[i].delete();
else
deleteDirectFiles(list[i]);// 非空目录进入递归函数
file.delete();// 删除空目录
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值