java download package Download file

A: some operations for file

1. Create a folder

private String CreateFile(String dir) {
File file = new File(dir);
if (!file.exists()) {
//创建文件夹
boolean mkdir = file.mkdir();

} else {

}
return dir;
}

2. Copy the files

private void copyFile(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}

3.删除文件
private void delFile(File file) {
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File f : listFiles) {
if (f.isDirectory()) {
delFile(f);
} else {
f.delete();
}
}
}
file.delete();
}

 

Two: controller file download operation

 

OutputStream out = response.getOutputStream();
byte[] data = FileToZipUtils.createZip(pdir);//这里根据项目里实际的地址去写  ,FileToZipUtils是一个工具类
response.reset();
//response.setHeader("Content-Disposition","attachment;fileName=file.zip");
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(pname+".zip", "UTF-8"));
response.addHeader("Content-Length", ""+data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
out.flush();
out.close();

 

Three: FileToZipUtils Tools

public class FileToZipUtils {

// Log
Private static Logger LoggerFactory.getLogger = log (FileToZipUtils.class);

/ ***
* becomes compressed zip file output stream
* /
public static byte [] createZip (String srcSource) throws Exception {
ByteArrayOutputStream the outputStream new new ByteArrayOutputStream = ( );
ZipOutputStream zip = new new ZipOutputStream (outputStream);
// target will be packaged into a zip file export
file file = new new file (srcSource);
createAllFile (zip, file, "");
IOUtils.closeQuietly (zip);
return outputStream.toByteArray ();
}

/ * * *
* files in the file
* /
public static void createAllFile (ZIP the ZipOutputStream, file file, the dir String) throws Exception {
// if the current folder is then further processed
if (file .isDirectory ()) {
// get the list information file
File [] = File.listFiles Files ();
// add a folder to a package directory
zip.putNextEntry (the ZipEntry new new (the dir + "/"));
the dir = dir.length ( ?) == 0 "": the dir + "/";
// cycle file folder package
for (int I = 0; I <files.length; I ++) {
createAllFile (ZIP, files [I], the dir + files [i] .getName () ); // recursive process
}
} is the else {// the current file, the packing process
// file stream input
BufferedInputStream new new BufferedInputStream BIS = (new new the FileInputStream (file));
the ZipEntry new new entry = the ZipEntry (the dir);
zip.putNextEntry (entry);
zip.write (FileUtils.readFileToByteArray (File));
IOUtils.closeQuietly (BIS);
zip.flush ();
zip.closeEntry ();
}
}

/ **
* source files will be stored in the directory sourceFilePath, packaged into fileName the name of the zip file, and place the next zipFilePath path
*
* @param sourceFilePath
*: to be a compressed file path
* @param zipFilePath
*: compressed storage path
@param fileName *
*: the compressed file name
* @return
* /
public static Boolean fileToZip (String sourceFilePath, zipFilePath String, String fileName) {
Boolean = in Flag to false;
file = a sourceFile new new file (sourceFilePath);
the FileInputStream FIS = null;
BIS = null BufferedInputStream;
a FileOutputStream fos = null;
the ZipOutputStream ZOS = null;

IF (sourceFile.exists () == to false) {
log.info ( "compressed file directory to be:" + sourceFilePath + "does not exist.");
} {the else
the try {
File ZipFile = new new File (zipFilePath + "/" fileName + + ".zip");
IF (zipFile.exists () {)
"presence directory named:" log.info (+ zipFilePath ". package file" + fileName + ".zip" +);
} the else {
file [] = SourceFiles sourceFile.listFiles ();
IF (== null || sourceFiles.length SourceFiles <. 1) {
log.info ( "compressed file directory to be:" + sourceFilePath + "file which does not exist, without compression. ");
} {the else
fos = new new a FileOutputStream (ZipFile);
ZOS the ZipOutputStream new new = (new new BufferedOutputStream The (fos));
byte [] = BUFS new new byte [1024 * 10];
for (int I = 0; I <sourceFiles.length; I ++) {
// create ZIP entity and add compressed
= New new ZipEntry the ZipEntry the ZipEntry (SourceFiles [I] .getName ());
zos.putNextEntry (ZipEntry);
// read the file to be compressed and written to the compressed bag
FIS new new = the FileInputStream (SourceFiles [I]);
BIS = BufferedInputStream new new (FIS, 1024 * 10);
int = 0 Read;
the while ((Read = bis.read (BUFS, 0, 1024 * 10)) = -1!) {
zos.write (BUFS, 0, Read);
}
}
In Flag = to true;
}
}
} the catch (a FileNotFoundException E) {
e.printStackTrace ();
the throw a RuntimeException new new (E);
} the catch (IOException E) {
e.printStackTrace ();
the throw a RuntimeException new new (E);
} the finally {
// Close stream
the try {
IF (BIS = null!)
bis.close ();
IF (null = ZOS!)
zos.close ();
} the catch (IOException E) {
e.printStackTrace ();
the throw a RuntimeException new new (E);
}
}
}
return In Flag;
}
/ **
* decompress the zip
*
* @param zipFilePath
full path * need to unzip the zip file
* @param unzipFilePath
save the decompressed file path *
* @param includeZipFileName
save the file name of the * decompressed file path contains a compressed file. true- comprising; does not contain false-
* /
@SuppressWarnings ( "an unchecked")
public static void the unzip (zipFilePath String, String unzipFilePath, Boolean includeZipFileName) throws Exception {
IF (StringUtils.isNotBlank (zipFilePath) || StringUtils.isNotBlank (unzipFilePath) ) {
File ZipFile = new new File (zipFilePath);
// save the file path if the file name of the compressed file containing the decompressed, the file name is appended to the extraction path
IF (includeZipFileName) {
String fileName = zipFile.getName ();
IF (the StringUtils .isNotEmpty (fileName)) {
fileName = fileName.substring (0, fileName.lastIndexOf ( "."));
}
unzipFilePath the File.separator + + fileName = unzipFilePath;
}
// Create the decompressed file path saved
file unzipFileDir = new File (unzipFilePath);
IF (unzipFileDir.exists () || unzipFileDir.isDirectory ()!!) {
unzipFileDir.mkdirs ();
}

// start extracting
the ZipEntry for the entry = null;
String = null entryFilePath, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, COUNT = 0, bufferSize = 1024;
byte [] Buffer = new new byte [bufferSize] ;
BufferedInputStream BIS = null;
BufferedOutputStream the BOS = null;
the ZipFile ZIP the ZipFile new new = (ZipFile);
the Enumeration <the ZipEntry> entries It = (the Enumeration <the ZipEntry>) zip.entries ();
// for each cycle is a file compression bag extracting
the while (entries.hasMoreElements ()) {
entry entries.nextElement = ();
// save the compressed package build a file extracting file full path
entryFilePath the File.separator + + = unzipFilePath entry.getName ();
// Construction after extracting the save folder path
index = entryFilePath.lastIndexOf (File.separator);
IF (index = -1!) {
entryDirPath entryFilePath.substring = (0, index);
} the else {
entryDirPath = "";
}
entryDir = new new File (entryDirPath);
// if the folder path does not exist, create folders
IF (entryDir.exists () || entryDir.isDirectory ()!!) {
entryDir.mkdirs ();
}

// Create extracting file
entryFile = new new File (entryFilePath);
IF (entryFile.exists ()) {
// detect whether to allow file deletion, if not delete, will throw SecurityException
the SecurityManager = new new securityManager the SecurityManager ();
securityManager. checkDelete (entryFilePath);
// delete the existing target file
entryFile.delete ();
}

// write file
BOS BufferedOutputStream The new new = (new new a FileOutputStream (entryFile));
BIS = new new BufferedInputStream (zip.getInputStream (entry));
! The while ((COUNT = bis.read (Buffer, 0, bufferSize)) = -1 ) {
bos.write (Buffer, 0, COUNT);
}
bos.flush ();
bos.close ();
}
zip.close (); // must remember to shut off, or in the same thread, you want to unzip after the temporary path, go to delete these temporary data, then it can not be deleted
}

}
}

Guess you like

Origin www.cnblogs.com/like9527/p/12103037.html