生活随笔
收集整理的这篇文章主要介绍了
java实现把一个大文件切割成N个固定大小的文件
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
这个好像是我一年前去面试时的一道面试题,分享一下!考 java I/O 的!
package com.johnny.test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; public class FenGeFile { public static final String SUFFIX = “.txt”; public static String[] divide(String name, long size) throws Exception { File file = new File(name); if (!file.exists() || (!file.isFile())) { throw new Exception(“指定文件不存在!”); } File parentFile = file.getParentFile(); long fileLength = file.length(); System.out.println(“文件大小:”+fileLength+” 字节”); if (size <= 0) { size = fileLength / 2; } int num = (fileLength % size != 0) ? (int) (fileLength / size + 1) : (int) (fileLength / size); String[] fileNames = new String[num]; FileInputStream in = new FileInputStream(file); long end = 0; int begin = 0; for (int i = 0; i < num; i++) { File outFile = new File(parentFile, file.getName() + i + SUFFIX); FileOutputStream out = new FileOutputStream(outFile); end += size; end = (end > fileLength) ? fileLength : end; for (; begin < end; begin++) { out.write(in.read()); } out.close(); fileNames[i] = outFile.getAbsolutePath(); } in.close(); return fileNames; } public static void readFileMessage(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String string = null; while ((string = reader.readLine()) != null) { System.out.println(string); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } public static void main(final String[] args) throws Exception { String name = “D:/boss/123.txt”; long size = 1024*1024*4; String[] fileNames = FenGeFile.divide(name, size); System.out.println(“文件” + name + “分割的结果如下:”); for (int i = 0; i < fileNames.length; i++) { System.out.println(fileNames[i] + “的内容如下:”); System.out.println(); } } }
转载于:https://blog.51cto.com/johnny84/1159616
总结
以上是生活随笔为你收集整理的java实现把一个大文件切割成N个固定大小的文件的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。