導出項目文件到本地指定目錄(zip)


一.導出項目文件到本地指定目錄。

 String filepath="";//項目文件路徑 ("static/img/123.png")

 InputStream  inputstream  = new  FileInputStream(fileName); 

String filename="";//文件名稱(123.png);

this.savePic(inputstream,filename)//調用 savePic方法

 

public static void savePic(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
  // 1、保存到臨時文件
  byte[] bs = new byte[1024];// 1K的數據緩沖
  int len;// 讀取到的數據長度
  File gkfile = new File("D:/downFile/img");// 輸出的文件流保存到本地文件
  if(!gkfile.exists()){//如果文件夾不存在
  gkfile.mkdir();//創建文件夾
  }else {
  gkfile.delete();
  gkfile.mkdir();
  }
  os = new FileOutputStream(gkfile.getPath() + File.separator + fileName,true);
  // 開始讀取
  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();
  }
  }
  }

 

二.將本地指定文件夾壓縮成.zip文件

List<File> fileList1 = new ArrayList<File>();
fileList1.add(new File("D:/downFile"));//填寫需要壓縮的文件夾路徑
FileOutputStream fos3 = new FileOutputStream(new File("D:/downFile.zip"));//填寫壓縮到文件夾路徑以及文件夾名稱
this.toZip(fileList1, fos3,true);//調用本地toZip方法

  

//1.srcFiles 需要壓縮的 文件夾路徑 列表2.out  壓縮文件輸出流3.KeepDirStructure是否保留原來的目錄結構,true:保留目錄結構;false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)

public static String toZip(List<File> srcFiles, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
String result = "false";
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
compress(srcFile,zos,srcFile.getName(),KeepDirStructure);
}
result = "true";
long end = System.currentTimeMillis();
System.out.println("1.1壓縮完成,耗時:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

 

三.刪除本地文件夾以及子文件夾方法

1.File file =new File(" D:/downFile")

public static void dripFile(File file){
if (file.isFile()) {
file.delete();
}
else {
File[] file1 = file.listFiles();
for (int i = 0; i < file1.length; i++) {
dripFile(file1[i].getAbsolutePath());
}
}
file.delete();
}

 

2.String drp="D:/downFile";

public static void dripFile(String drp){
File file =new File(drp);
if (file.isFile()) {
file.delete();
}
else {
File[] file1 = file.listFiles();
for (int i = 0; i < file1.length; i++) {
dripFile(file1[i].getAbsolutePath());
}
}
file.delete();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM