使用阿里云服务器等
上传
controller层:
/**
* 文件上传
*
* @param reportCode
* @param moduleId
* @param fileName
* @param file
* @return
* @throws Exception
*/
@Value("${ctj.fineReport.host}")
private String ip;
@Value("${ctj.fineReport.port}")
private int port;
@Value("${ctj.fineReport.username}")
private String username;
@Value("${ctj.fineReport.password}")
private String password;
@Value("${ctj.fineReport.path}")
private String path;
@ApiOperation(value = "文件上传(江苏预算执行报表文件)")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResultData<Boolean> upload(@RequestParam(value = "file") MultipartFile file,
@RequestParam String admDivCode,
@RequestParam int busiYear) {
try {
Ftp ftp = Ftp.getSftpUtil(ip, port, username, password);
File file1 = multipartFileToFile(file);
String fileName = file.getOriginalFilename().trim();
String destFileName = "/" + admDivCode + "/" + busiYear + "/" + path;
fileName = URLDecoder.decode(fileName, "UTF-8");
destFileName = URLDecoder.decode(destFileName, "UTF-8");
ftp.upload(destFileName, file1, ftp, fileName);
Report report = new Report();
String id = UUID.randomUUID().toString().replace("-", "");
report.setReport_id(id);
report.setReport_name(fileName);
report.setTenant_id(Integer.valueOf(admDivCode));
report.setUpdate_time(new Date());
report.setIs_deleted(2);
reportMapper.insertReport(report);
return new ResultData("0000", "上传成功", true);
} catch (Exception e) {
logger.error("上传失败,异常信息:{}", e.getMessage(), e);
return new ResultData("9999", "上传失败:" + e.getMessage(), null);
}
}
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
logger.error("获取流文件失败!", e.getMessage(), e);
}
}
yml配置文件
### 配置类参数
ctj:
# 判断文件上传类型
fileTypes:
- html
- jsp
- js
- css
- php
- py
- sh
fineReport:
host: 39.101.189.62
port: 22
username: root
password: 密码
path: 1
ftp工具类:
package grp.pt.frs.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import com.jcraft.jsch.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Ftp {
//打印log日志
private static final Log logger = LogFactory.getLog(Ftp.class);
private static Date last_push_date = null;
private Session sshSession;
private ChannelSftp channel;
private static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>();
private Ftp(String host, int port, String username, String password) throws Exception {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
//根据用户名,密码,端口号获取session
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
//修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no,解决用户不能远程登录
sshSession.setConfig("userauth.gssapi-with-mic", "no");
//为session对象设置properties,第一次访问服务器时不用输入yes
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect();
//获取sftp通道
channel = (ChannelSftp) sshSession.openChannel("sftp");
channel.connect();
logger.info("连接ftp成功!" + sshSession);
}
/**
* 是否已连接
*
* @return
*/
private boolean isConnected() {
return null != channel && channel.isConnected();
}
/**
* 获取本地线程存储的sftp客户端
*
* @return
* @throws Exception
*/
public static Ftp getSftpUtil(String host, int port, String username, String password) throws Exception {
//获取本地线程
Ftp sftpUtil = sftpLocal.get();
if (null == sftpUtil || !sftpUtil.isConnected()) {
//将新连接防止本地线程,实现并发处理
sftpLocal.set(new Ftp(host, port, username, password));
}
return sftpLocal.get();
}
/**
* 释放本地线程存储的sftp客户端
*/
public static void release() {
if (null != sftpLocal.get()) {
sftpLocal.get().closeChannel();
logger.info("关闭连接" + sftpLocal.get().sshSession);
sftpLocal.set(null);
}
}
/**
* 关闭通道
*
* @throws Exception
*/
public void closeChannel() {
if (null != channel) {
try {
channel.disconnect();
} catch (Exception e) {
logger.error("关闭SFTP通道发生异常:", e);
}
}
if (null != sshSession) {
try {
sshSession.disconnect();
} catch (Exception e) {
logger.error("SFTP关闭 session异常:", e);
}
}
}
/**
* @param directory 上传ftp的目录
* @param file 本地文件目录
*/
public void upload(String directory, File file, Ftp ftp, String reportCode) throws Exception {
try {//执行列表展示ls 命令
//channel.ls(directory); //执行盘符切换cd 命令
//channel.cd(directory);
ftp.createDir(directory, ftp.channel);
//List<File> files = getFiles(uploadFile, new ArrayList<File>());
//for (int i = 0; i < files.size(); i++) {
//File file = files.get(i);
InputStream input = new BufferedInputStream(new FileInputStream(file));
String s = reportCode;
channel.put(input, s);
try {
if (input != null) input.close();
} catch (Exception e) {
e.printStackTrace();
logger.error(file.getName() + "关闭文件时.....异常!" + e.getMessage());
}
if (file.exists()) {
boolean b = file.delete();
logger.info(file.getName() + "文件上传完毕!删除标识:" + b);
}
//}
} catch (Exception e) {
logger.error("【子目录创建中】:", e);
//创建子目录
channel.mkdir(directory);
}
}
//获取文件
public List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (null == last_push_date) {
return true;
} else {
long modifyDate = file.lastModified();
return modifyDate > last_push_date.getTime();
}
}
});
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
if (null == last_push_date) {
last_push_date = new Date(file.lastModified());
} else {
long modifyDate = file.lastModified();
if (modifyDate > last_push_date.getTime()) {
last_push_date = new Date(modifyDate);
}
}
}
}
return files;
}
/**
* 判断目录是否存在
*
* @param directory 路径
* @return
*/
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = this.channel.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 方法功能说明:目录不存在时创建目录
*
* @return void
* @throws
* @参数: @param path
*/
public void mkdirs(String path) {
File file = new File(path);
String fs = file.getParent();
file = new File(fs);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 创建一个文件目录
*/
public void createDir(String createpath, ChannelSftp sftp) {
try {
if (isDirExist(createpath)) {
this.channel.cd(createpath);
return;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
this.channel.cd(createpath);
} catch (SftpException e) {
logger.error("创建路径错误:" + createpath);
//throw new SystemException("创建路径错误:" + createpath);
}
}
}
mapper层:
@Insert("insert into GAP_REPORT (report_id ,report_name ,tenant_id ,update_time,is_deleted) values ("
+ "#{report.report_id, jdbcType=VARCHAR},"
+ "#{report.report_name, jdbcType=VARCHAR},"
+ "#{report.tenant_id, jdbcType=INTEGER},"
+ "#{report.update_time, jdbcType=DATE},"
+ "#{report.is_deleted, jdbcType=INTEGER}"
+ ")")
Boolean insertReport(@Param("report") Report report);
下载
controller层:
/**
* 文件下载
*
* @param id
* @param admDivCode
* @param busiYear
* @return
*/
@ApiOperation(value = "文件下载(江苏预算执行报表文件)")
@GetMapping("/download/{id}")
public void downloadCacheFile(@PathVariable("id") String id,
@RequestParam String admDivCode,
@RequestParam int busiYear,
HttpServletResponse response) {
try {
String fileName = reportMapper.selectOneReportName(id);
String fpath = "/" + admDivCode + "/" + busiYear + "/" + path + "/";
SFTPUtil sFTPUtil = new SFTPUtil(ip, port, username, password);
sFTPUtil.connect();
sFTPUtil.downloadFile(fpath, fileName, response);
} catch (Exception e) {
logger.error("下载失败,异常信息:{}", e.getMessage(), e);
}
}
mapper层:
@Select("select report_name from GAP_REPORT where report_id = #{id}")
String selectOneReportName(@Param("id") String id);
SFTPUtil工具类:
package grp.pt.frs.util;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.Data;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Properties;
@Data
public class SFTPUtil {
private String host;//服务器连接ip
private String username;//用户名
private String password;//密码
private int port;//端口号
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPUtil(){}
public SFTPUtil(String host, int port, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public SFTPUtil(String host, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
}
/**
* 通过SFTP连接服务器
*/
public void connect()
{
try
{
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect()
{
if (this.sftp != null)
{
if (this.sftp.isConnected())
{
this.sftp.disconnect();
}
}
if (this.sshSession != null)
{
if (this.sshSession.isConnected())
{
this.sshSession.disconnect();
}
}
}
/**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
*/
public void deleteSFTP(String directory, String deleteFile)
{
try
{
sftp.rm(directory + deleteFile);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @return
*/
public void downloadFile(String remotePath, String remoteFileName, HttpServletResponse response) {
byte[] buf = new byte[1024];
// 获取输出流
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
String rfileName = URLDecoder.decode(remotePath + remoteFileName, "UTF-8");
InputStream in = sftp.get(rfileName);
response.reset();
// 不同类型的文件对应不同的MIME类型
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(remoteFileName, "UTF-8"));
int len = -1;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
附录
stfp下载的工具类(支持批量下载和打包)SFTPUtil
package com.fine.tools.utils;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import javax.servlet.http.HttpServletResponse;
public class SFTPUtil {
private String host = "127.0.0.1";//服务器连接ip
private String username = "root";//用户名
private String password = "123";//密码
private int port = 22;//端口号
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPUtil(){}
public SFTPUtil(String host, int port, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public SFTPUtil(String host, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
}
/**
* 通过SFTP连接服务器
*/
public void connect()
{
try
{
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect()
{
if (this.sftp != null)
{
if (this.sftp.isConnected())
{
this.sftp.disconnect();
}
}
if (this.sshSession != null)
{
if (this.sshSession.isConnected())
{
this.sshSession.disconnect();
}
}
}
/**
* 批量下载文件
* @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
public List<File> batchDownLoadFile(String remotePath, String localPath,
String fileFormat, String fileEndFormat, boolean del)
{
List<File> fileList = new ArrayList<File>();
File file = null;
try
{
Vector v = listFiles(remotePath);
if (v.size() > 0)
{
Iterator it = v.iterator();
while (it.hasNext())
{
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir())
{
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
{
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat))
{
file = downloadFile(remotePath, filename,localPath, filename);
if (file!=null)
{
fileList.add(file);
if (file!=null && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
{
if (filename.startsWith(fileFormat))
{
file = downloadFile(remotePath, filename, localPath, filename);
if (file!=null)
{
fileList.add(file);
if (file!=null && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
{
if (filename.endsWith(fileEndFormat))
{
file = downloadFile(remotePath, filename,localPath, filename);
if (file!=null)
{
fileList.add(file);
if (file!=null && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else
{
file = downloadFile(remotePath, filename,localPath, filename);
if (file!=null)
{
fileList.add(file);
if (file!=null && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
}
catch (SftpException e)
{
e.printStackTrace();
}
return fileList;
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public File downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
{
FileOutputStream fieloutput = null;
File file = null;
try
{
file = new File(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
fieloutput.close();
return file;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally
{
if (null != fieloutput)
{
try
{
fieloutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return file;
}
public InputStream downloadStream(String directory, String downloadFile){
try{
if(directory != null && !"".equals(directory)){
sftp.cd(directory);
}
return sftp.get(downloadFile);
}catch (SftpException e){
e.printStackTrace();
}
return null;
}
/**
* 上传单个文件
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
{
FileInputStream in = null;
try
{
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量上传文件
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @param del:上传后是否删除本地文件
* @return
*/
public boolean bacthUploadFile(String remotePath, String localPath,
boolean del)
{
try
{
connect();
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1)
{
if (this.uploadFile(remotePath, files[i].getName(),
localPath, files[i].getName())
&& del)
{
deleteFile(localPath + files[i].getName());
}
}
}
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
this.disconnect();
}
return false;
}
/**
* 删除本地文件
* @param filePath
* @return
*/
public boolean deleteFile(String filePath)
{
File file = new File(filePath);
if (!file.exists())
{
return false;
}
if (!file.isFile())
{
return false;
}
boolean rs = file.delete();
return rs;
}
/**
* 创建目录
* @param createpath
* @return
*/
public boolean createDir(String createpath)
{
try
{
if (isDirExist(createpath))
{
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry)
{
if (path.equals(""))
{
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString()))
{
sftp.cd(filePath.toString());
}
else
{
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
return true;
}
catch (SftpException e)
{
e.printStackTrace();
}
return false;
}
/**
* 判断目录是否存在
* @param directory
* @return
*/
public boolean isDirExist(String directory)
{
boolean isDirExistFlag = false;
try
{
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
}
catch (Exception e)
{
if (e.getMessage().toLowerCase().equals("no such file"))
{
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
*/
public void deleteSFTP(String directory, String deleteFile)
{
try
{
sftp.rm(directory + deleteFile);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 将文件打包
* @param srcfile:文件集合
* @param zipFileName:生成的文件名
*/
public static void zipFiles(List<File> srcfile, String zipFileName, HttpServletResponse response) throws IOException {
byte[] buf = new byte[1024];
// 获取输出流
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream in = null;
ZipOutputStream out = null;
try {
response.reset();
// 不同类型的文件对应不同的MIME类型
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName + ".zip", "UTF-8"));
// ZipOutputStream类:完成文件或文件夹的压缩
out = new ZipOutputStream(bos);
for (int i = 0; i < srcfile.size(); i++) {
in = new FileInputStream(srcfile.get(i));
// 给列表中的文件单独命名
out.putNextEntry(new ZipEntry(srcfile.get(i).getName()));
int len = -1;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
out.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
/**
* 列出目录下的文件
*
* @param directory:要列出的目录
* @return
* @throws SftpException
*/
public Vector listFiles(String directory) throws SftpException
{
return sftp.ls(directory);
}
public String getHost()
{
return host;
}
public void setHost(String host)
{
this.host = host;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public int getPort()
{
return port;
}
public void setPort(int port)
{
this.port = port;
}
public ChannelSftp getSftp()
{
return sftp;
}
public void setSftp(ChannelSftp sftp)
{
this.sftp = sftp;
}
}
操作本地文件的工具类
package com.fine.tools.utils;
import java.io.File;
/*
* 操作本地文件工具类
*/
public class LocalUtil {
//创建本地文件夹
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
//创建目录
if (dir.mkdirs()) {
return true;
} else {
return false;
}
}
//删除文件夹
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
//删除指定文件夹下的所有文件
public static boolean delAllFile(String path) throws InterruptedException {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
//由于关闭io流后文件仍然被占用,因此直接采用gc垃圾回收等待两秒删除
System.gc();
Thread.sleep(2000);
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
}
}