读书人

java 将文件打包并上载的工具类

发布时间: 2012-08-22 09:50:35 作者: rapoo

java 将文件打包,并下载的工具类
??? ??? toClient.write(buffer);
??? ??? toClient.flush();
??? ??? toClient.close();
??? ??? } catch (IOException ex) {
??? ??? ex.printStackTrace();
??? ??? }finally{
??? ??? ??? ?try {
??? ??????????? ??? File f = new File(file.getPath());
??? ??????????? ??? f.delete();
??? ??? ??? ??? } catch (Exception e) {
??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? }
??? ??? }
??? ??? return response;
??? }

/**?
???? * 根据输入的文件与输出流对文件进行打包
???? * @param File
???? * @param org.apache.tools.zip.ZipOutputStream
???? */
??? public static void zipFile(File inputFile,
??? ??? ??? ZipOutputStream ouputStream) {
??? ??? try {
??? ??? ??? if(inputFile.exists()) {
??? ??? ??? ??? /**如果是目录的话这里是不采取操作的,
??? ??? ??? ??? ?* 至于目录的打包正在研究中*/
??? ??? ??? ??? if (inputFile.isFile()) {
??? ??? ??? ??? ??? FileInputStream IN = new FileInputStream(inputFile);
??? ??? ??? ??? ??? BufferedInputStream bins = new BufferedInputStream(IN, 512);
??? ??? ??? ??? ??? //org.apache.tools.zip.ZipEntry
??? ??? ??? ??? ??? ZipEntry entry = new ZipEntry(inputFile.getName());
??? ??? ??? ??? ??? ouputStream.putNextEntry(entry);
??? ??? ??? ??? ??? // 向压缩文件中输出数据??
??? ??? ??? ??? ??? int nNumber;
??? ??? ??? ??? ??? byte[] buffer = new byte[512];
??? ??? ??? ??? ??? while ((nNumber = bins.read(buffer)) != -1) {
??? ??? ??? ??? ??? ??? ouputStream.write(buffer, 0, nNumber);
??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? // 关闭创建的流对象??
??? ??? ??? ??? ??? bins.close();
??? ??? ??? ??? ??? IN.close();
??? ??? ??? ??? } else {
??? ??? ??? ??? ??? try {
??? ??? ??? ??? ??? ??? File[] files = inputFile.listFiles();
??? ??? ??? ??? ??? ??? for (int i = 0; i < files.length; i++) {
??? ??? ??? ??? ??? ??? ??? zipFile(files[i], ouputStream);
??? ??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? } catch (Exception e) {
??? ??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? ??? }
??? ??? ??? ??? }
??? ??? ??? }
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? }

}

读书人网 >Web前端

热点推荐