前言
紀錄使用Java串流類別來操作檔案,並用Base64來讀寫各種檔案類型(pdf/pptx/…)
壓縮檔包檔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import java.io.*; import java.util.Base64; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
public class Base64Transformator { public static String saveBase64ToFile(String name, String userFileName) { String defaultPath = String.format("D:\\%tF\\%s\\", new Date(), name); File file = new File(defaultPath); if(!file.exists()) { file.mkdirs(); } String base64String = "UEsDBBQABg......."; String fileName = defaultPath + userFileName; byte dearr[] = Base64.getDecoder().decode(base64String); try(FileOutputStream fos = new FileOutputStream(new File(fileName))) { fos.write(dearr); } catch (Exception e) { e.printStackTrace(); } return fileName; } public static void zipMultipleFile(String path) { String zipFileName = path + "result.zip"; File folder = new File(path); File[] listOfFiles = folder.listFiles(); if(listOfFiles != null && listOfFiles.length > 0) { try(ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName))) { for (File file : listOfFiles) { if (file.isFile() && !file.getName().equals(zipFileName)) { zipOutputStream.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int readLen; byte[] buffer = new byte[1024]; while ((readLen = bis.read(buffer)) != -1) { zipOutputStream.write(buffer, 0, readLen); } System.out.println(file.getName()); } } } catch (Exception e) { e.printStackTrace(); } }
} public static void main(String[] args) { String defaultPath = String.format("D:\\%tF\\Redick\\", new Date()); zipMultipleFile(defaultPath); } }
|
參考
- File to Base64
- https://www.mdeditor.tw/pl/gxgA/zh-tw