java FileUtils

import lombok.extern.slf4j.Slf4j; import sun.misc.BASE64Encoder; import java.io.*; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.util.Base64; import java.util.HashMap; import java.util.Map; @Slf4j public class FileUtils { public static Map<String,String> getMapEncodeToStringData(String fileName, String filePath, Map<String,String> map) throws IOException { Base64.Encoder encoder = Base64.getEncoder(); //byte[]轉換爲base64 if(CommonUtils.notEmpty(fileName)) { map.put(fileName, encoder.encodeToString(filePath.getBytes())); } return map; } public static Map<String,String> getMapFileScannerData(String fileName, String filePath, Map<String,String> map) throws IOException { byte[] bytes = toByteArray(filePath+fileName); BASE64Encoder encode = new BASE64Encoder(); //byte[]轉換爲base64 if(CommonUtils.notEmpty(fileName)) { map.put(fileName, encode.encode(bytes)); } return map; } public static Map<String,String> getMapFileScannerData(String fileName,InputStream inputStream, Map<String,String> map) throws IOException { byte[] bytes = toByteArray(inputStream); BASE64Encoder encode = new BASE64Encoder(); //byte[]轉換爲base64 if(CommonUtils.notEmpty(fileName)) { map.put(fileName, encode.encode(bytes)); } return map; } public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } public byte[] getContent(String filePath) throws IOException { File file = new File(filePath); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { System.out.println("file too big..."); return null; } FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // 確保所有數據均被讀取 if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fi.close(); return buffer; } /** * the traditional io way * * @param filename * @return * @throws IOException */ public static byte[] toByteArray(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } bos.close(); } } /** * NIO way * * @param filename * @return * @throws IOException */ public static byte[] toByteArray2(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { // do nothing // System.out.println("reading"); } return byteBuffer.array(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Mapped File way MappedByteBuffer 可以在處理大文件時,提升性能 * * @param filename * @return * @throws IOException */ public static byte[] toByteArray3(String filename) throws IOException { FileChannel fc = null; try { fc = new RandomAccessFile(filename, "r").getChannel(); MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load(); System.out.println(byteBuffer.isLoaded()); byte[] result = new byte[(int) fc.size()]; if (byteBuffer.remaining() > 0) { // System.out.println("remain"); byteBuffer.get(result, 0, byteBuffer.remaining()); } return result; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } } //刪除指定文件夾下的所有文件 public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);//先刪除文件夾裏面的文件 delFolder(path + "/" + tempList[i]);//再刪除空文件夾 flag = true; } } return flag; } //刪除文件夾 public static void delFolder(String folderPath) { try { delAllFile(folderPath); //刪除完裏面所有內容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //刪除空文件夾 } catch (Exception e) { e.printStackTrace(); } } /** *@author: victor *@date: 2021-12-02 18:46 *@description: */ public static boolean writeStringToFile(String filePath,String content,Boolean overWritten) { BufferedWriter bw=null; try { File file=new File(filePath); if(file.exists()){ if(file.isDirectory()){ throw new RuntimeException("error happen,exists a dir with the same name"); }else{ if(!Boolean.TRUE.equals(overWritten)) { throw new RuntimeException("error happen,file \"" + filePath + "\"already exists"); } } } File dir = file.getParentFile(); if(!dir.exists()){ dir.mkdirs(); } bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8")); bw.write(content); return true; } catch (Exception e) { log.error(e.getMessage()); }finally { close(bw); } return false; } public static String readFileContent(String filePath) { BufferedReader reader = null; try { File file = new File(filePath); if(!file.exists()||!file.isFile()){ return null; } reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); StringBuffer sbf = new StringBuffer(); String tempStr; while ((tempStr = reader.readLine()) != null) { sbf.append(tempStr); } return sbf.toString(); } catch (IOException e) { e.printStackTrace(); } finally { close(reader); } return null; } /** *@author: victor *@date: 2021-12-02 19:13 *@description: */ private static void close(AutoCloseable autoCloseable){ if(autoCloseable!=null) { try { autoCloseable.close(); } catch (Exception e) { e.printStackTrace(); } } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章