import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileToHome {
public static String ZIP_PATH="E:\\下载\\测试";
public static final String FILE_PATH="E:\\下载\\测试";
//下载xls文件 workbook 是文件,fileName下载后文件名称,path文件存放本地路径
// Workbook workbook = ExcelUtil.getWorkbook(headers, datas); //这里用了一个工具类
// FileToHome.savePic(workbook,"1.xls","D:\\Y2\\a");
public static void savePic(Workbook workbook, String fileName, String path) {
InputStream inputStream=null;
OutputStream os = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] barray = bos.toByteArray();
inputStream = new ByteArrayInputStream(barray);
// 2、保存到临时文件
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//下载网络文件
//urlpath是下载的路径,path是存放的路径,fileName是文件名称带文件名和后缀
//FileToHome.downHttp("http://abc.docx","D:\\Y2","a.docx");
public static boolean downHttp(String urlpath, String path, String fileName) {
boolean zhen=false;
// 下载网络文件
InputStream inStream =null;
FileOutputStream fs =null;
try {
int bytesum = 0;
int byteread = 0;
// String urlpath="abc.docx";
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
// path="D:\\Y2";
File tempFile = new File(path+"\\"+fileName);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
inStream = conn.getInputStream();
fs = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
zhen=true;
} catch (Exception e) {
zhen=false;
e.printStackTrace();
}finally {
// 完毕,关闭所有链接
try {
fs.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return zhen;
}
//打压缩包
//FileToHome.fileToZip(FileToHome.FILE_PATH+"\\"+path, fos1,true);
//srcDir打包文件路径或目录,out输出流,keepDirstructure是否保留结构,可能遇见重名(会出错)
public static boolean fileToZip(String srcDir, OutputStream out, boolean KeepDirStructure){
boolean cuo=false;
// long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try{
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
// long end = System.currentTimeMillis();
// System.out.println("压缩完成,耗时:" + (end - start) +" ms");
FileToHome.clearFiles(srcDir);
cuo=true;
}catch (Exception e) {
e.printStackTrace();
cuo=false;
System.out.println("zip压缩出错");
}finally{
if(zos != null){
try {
zos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return cuo;
}
private static final int BUFFER_SIZE = 2 * 1024;
//复制文件到压缩包中
//sorceFile文件或目录,zos是zip的输出流,name是zip文件名称,keepDirStructure是否保留原文件结构
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}else{
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else{
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
}else{
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
//浏览器下载zip包
//FileToHome.DownZipFile(fileName,request,response);
//下载后的名称,request和response
public static void DownZipFile(String ZipName,HttpServletRequest request, HttpServletResponse response){
try {
//调用FileToZip接口生成压缩包
// boolean flag = FileToHome.fileToZip(sourceFilePath, zipFilePath, fileName);
boolean flag =true;
if(flag){
System.out.println("文件打包成功!");
}else{
System.out.println("文件打包失败!");
}
//Zip压缩包路径
String path = FileToHome.ZIP_PATH+"\\"+ZipName;
File file = new File(path);
if(file.length()<1||file==null){
System.out.println("zip文件不存在!");
}else{
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String(ZipName.getBytes("ISO8859-1"), "UTF-8"));
response.setContentLength((int) file.length());
response.setContentType("application/zip");// 定义输出类型
FileInputStream fis = new FileInputStream(file);
BufferedInputStream buff = new BufferedInputStream(fis);
byte[] b = new byte[1024];// 相当于我们的缓存
long k = 0;// 该值用于计算当前实际下载了多少字节
OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
// 开始循环下载
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
myout.write(b, 0, j);
}
// 刷新此输出流并强制将所有缓冲的输出字节被写出
myout.flush();
//关闭流
myout.close();
buff.close();
fis.close();
//删除生成的压缩包文件
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//删除指定文件夹里所有文件及文件夹
public static void clearFiles(String rootpath){
File file=new File(rootpath);
if(file.exists()){
deleteFiles(file);
}
}
//递归删除
public static void deleteFiles(File file){
if(file.isDirectory()){
File[] files=file.listFiles();
for(int i=0;i<files.length;i++){
deleteFiles(files[i]);
}
}
file.delete();
}
}
java程序创建文件,删除文件,下载文件,删除文件,对文件文件夹的操作,和打包文件,web前端进行下载打包文件
最新推荐文章于 2022-07-17 20:59:32 发布