public class FileUtil { /** * 创建目录,如果目录不存在这创建目录 * * @param path 目录路径 */ public static void mkdirs(String path) { File file = new File(path); if (!file.exists()) { file.mkdirs(); } } /** * 删除文件 * * @param path */ public static void deleteFile(String path) { File file = new File(path); if (file.exists()) { file.delete(); } } /** * 创建文件 * * @param stream 文件流 * @param path 文件保存路径 * @throws IOException */ public static void createFile(InputStream stream, String path) throws IOException { FileOutputStream outputStream = null; int byteCount; try { outputStream = new FileOutputStream(path); byte[] bytes = new byte[1024]; while ((byteCount = stream.read(bytes)) != -1) { outputStream.write(bytes, 0, byteCount); } } finally { closeOutputStream(outputStream); closeInputStream(stream); } } /** * 关闭 InputStream 流 * * @param stream InputStream 流对象 */ private static void closeInputStream(InputStream stream) { try { stream.close(); } catch (IOException e) { } } /** * 关闭 OutputStream 流 * * @param outputStream OutputStream 流对象 */ private static void closeOutputStream(OutputStream outputStream) { try { outputStream.close(); } catch (IOException e) { } } /** * MultipartFile 转 File * * @param file * @throws Exception */ public static File multipartFileToFile(MultipartFile file) throws Exception { File toFile = null; if (!"".equals(file) && file.getSize() > 0) { InputStream ins; ins = file.getInputStream(); toFile = new File(file.getOriginalFilename()); inputStreamToFile(ins, toFile); ins.close(); } return toFile; } /** * 获取流文件 */ private static void inputStreamToFile(InputStream ins, File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); } catch (Exception e) { e.printStackTrace(); } } public static String getPath() { return FileUtil.class.getResource("/").getPath(); } }
FileUtil
最新推荐文章于 2021-11-18 16:45:40 发布