FileUtil.java import org.apache.commons.io.IOUtils; import java.io.*; public class FileUtil { /** * 切割文件 * @param targetFile 源文件 * @param outFolder 切割文件的输出目录 * @param chunkSize 切割文件大小 * @throws Exception */ public static void splitFile(File targetFile, File outFolder, long chunkSize) throws Exception{ InputStream inputStream = null; try { long totalSize = targetFile.length(); int chunkCount = (int) Math.ceil((double)totalSize / chunkSize); if(!outFolder.exists()) { outFolder.mkdirs(); } inputStream = new FileInputStream(targetFile); for (int i = 0; i < chunkCount; i++) { String filepath = outFolder.getPath() + File.separator + targetFile.getName() + "."+ System.currentTimeMillis(); File file = new File(filepath); OutputStream outputStream = new FileOutputStream(file); try { IOUtils.copyLarge(inputStream, outputStream, 0L, chunkSize); outputStream.flush(); } catch (Exception e) { throw e; } finally { IOUtils.closeQuietly(outputStream); } } }catch (Exception e) { throw e; }finally { IOUtils.closeQuietly(inputStream); } } } --------------------------------------------------------------------------------------- PathUtil.javaimport org.apache.commons.io.FileUtils; import java.io.File; import java.net.URL; public class PathUtil { /** * 获取文件的根路径 * @param path 文件绝对路径 * @return */ public static String getRootPath(String path){ String sep = File.separator; if(path.indexOf(sep) == -1){ return path; } return path.substring(0, path.indexOf(sep) + 1); } /** * 根据目录名称拼接文件路径 * @param path 原始文件路径 * @param fragement 目录名称 * @return */ public static String joinPath(String path, String... fragement){ if(!path.endsWith(File.separator)) { path += File.separator; } for(String frag : fragement){ path += frag + File.separator; } return path; } /** * 根据URL获取根路径 * @param url * @return */ public static String getRootPath(URL url){ String path = FileUtils.toFile(url).getPath(); return getRootPath(path); } }
FileUtil(大文件分割)
最新推荐文章于 2022-06-10 10:48:12 发布