使用FileChannel复制文件的速度比BufferedInputStream/BufferedOutputStream复制文件的速度快。而且FileChannel是线程安全的。
/**
* 复制文件,使用文件通道的方式
* @param sourceFile
* @param destFile
*/
public void fileChannelCopy(File sourceFile, File destFile) {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel in = null;
FileChannel out = null;
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(destFile);
in = fis.getChannel();
out = fos.getChannel();
in.transferTo(0, in.size(), out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
in.close();
fos.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
创建文件夹
String dirStr = JSFUtils.getInitParameter("xspic_path") + "temp";
//web.xml配置的context-param参数,值为/jwxt/picture/xspic/
File directory = new File(dirStr);
if (directory.exists()) {
this.removeDir(directory); //如果目录存在,则先删除再创建
}
directory.mkdirs();
/**
* 删除文件夹下所有文件,递归
* @param dir
* @return
*/
private boolean removeDir(File dir) {
if (dir.isDirectory()) {
String[] fileList = dir.list();
for (String file : fileList) {
boolean flag = removeDir(new File(dir, file));
if (!flag) {
return false;
}
}
}
return dir.delete(); //此时目录为空,可以删除
}
业务代码
/**
* 批量下载
* @param facesContext
* @param outputStream
*/
public void downloadAll(FacesContext facesContext,
OutputStream outputStream) {
String dirStr = JSFUtils.getInitParameter("xspic_path") + "temp";
//web.xml配置的context-param参数,值为/jwxt/picture/xspic/
File directory = new File(dirStr);
if (directory.exists()) {
this.removeDir(directory); //如果目录存在,则先删除再创建
}
directory.mkdirs(); //创建目录
String path = null;
for (Row row : this.xszpxxValue) {
this.fileName = (String)row.getAttribute("Xm") + row.getAttribute("Sfzjh") + ".jpg";
path = (String)(row.getAttribute("Imagepath") == null ? "" : row.getAttribute("Imagepath"));
path = path.substring(0, path.lastIndexOf("/")) + ".jpg";
File sourceFile = new File(path);
File destFile = new File(directory, fileName);
if (sourceFile.exists()) {
this.fileCopy(sourceFile, destFile);
}
}
String zipFilePath = JSFUtils.getInitParameter("xspic_path") + File.separator + jxbmc + ".zip";
CHZipUtils.zip(dirStr, zipFilePath); //打包成zip格式
//this.zipFileName = jxbmc + "zip"; //教学班名称作为下载文件名
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(zipFilePath));
IOUtils.copy(fis, outputStream);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}