Java FileUtils
/** * Created by xxx on 2023-11-06. */ import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletResponse; import java.io.*; @Slf4j public class FileUtils { private static final int CACHE_SIZE = 1024; /** * 根据路径和文件名后缀创建文件 * * @param path * @param suffix * @return */ public static String buildFile(String path, String suffix) { //获取文件路径以及文件名 if (suffix == null || suffix.equals("")) { } else { path = path + suffix; } File file = new File(path); //若文件不存在 if (!file.exists()) { try { //创建文件 file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } return path; } /** * 根据路径创建文件夹 * * @param path * @return */ public static String buildDirectory(String path) { File file = new File(path); //若文件不存在 if (!file.exists()) { try { //创建文件 file.mkdirs(); } catch (Exception e) { e.printStackTrace(); } } return path; } /** * 视频流传给前端 * * @param response * @param bytes */ public static void getVideoOutStream(HttpServletResponse response, byte[] bytes) { OutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write(bytes); outputStream.flush(); } catch (Exception e) { log.error("error", e); throw new RuntimeException(e); } finally { try { outputStream.close(); } catch (IOException e) { log.error("error", e); } } } /** * 将Byte数组转换成文件 * * @param bytes byte数组 * @param filePath 文件路径 如 D://test/ 最后“/”结尾 * @param fileName 文件名 */ public static void fileToBytes(byte[] bytes, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { if (!filePath.endsWith("/")) { filePath += "/"; } file = new File(filePath + fileName); if (!file.getParentFile().exists()) { //文件夹不存在 生成 file.getParentFile().mkdirs(); } fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static byte[] fileToBytes(File file) throws Exception { byte[] data = new byte[0]; if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } }
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号