import java.io.*; import java.util.Scanner; import static java.awt.Desktop.getDesktop; public class IOSplit { public static void main(String[] args) throws IOException { /** * 对文件进行分割: * 1.首先,先通过调用File的方法去确定文件是否存在(.exists()),以及 * 获得文件的大小(字节:.length())。 * 2.找到文件后,将文件存入数组中(.read(byte[] b)) * 3.通过输入需要分隔的大小将文件循环(for)写入新的文件中(.write(byte[] b, int off, int len)) * byte[] b : 字节数组 * int off : 从byte[] b的下标为off的元素开始写入 * int len : 写入的长度 */ Scanner in = new Scanner(System.in); //文件 File file; //文件路径 String path = null; //判断文件是否存在 do { System.out.println("请输入文件路径:"); path = in.next(); file = new File(path); if (!file.exists()){ System.out.println("文件不存在!"); } } while (!file.exists()); //获取文件的字节长度 int length = (int)file.length(); System.out.print("文件大小:" + file.length()); System.out.println("请输入文件分割的大小:(单位byte)"); int splitByte = in.nextInt(); System.out.println("开始分割....."); //读取文件到字节数组中 FileInputStream fileInputStream = new FileInputStream(path); byte[] inBuffer = new byte[length]; fileInputStream.read(inBuffer); fileInputStream.close(); //通过for循环分割文档 for (int i = 1; length > 0; i++) { //输出文件路径path,并在末尾添加编号i FileOutputStream fileOutputStream = new FileOutputStream(path + i); //为防止数组下标越界,当剩余长度小于分割长度时,分割长度为length if (length > splitByte){ //splitByte * (i - 1)从0开始,每隔splitByte分割一次,长度为splitByte fileOutputStream.write(inBuffer,splitByte * (i - 1),splitByte); }else{ fileOutputStream.write(inBuffer,splitByte * (i - 1),length); } //分割后长度 - splitByte length = length - splitByte; System.out.println(path + i); fileOutputStream.close(); } System.out.println("分隔完毕!"); //打开输入文件夹 StringBuffer cPath = new StringBuffer(path); String newPath = cPath.substring(0,cPath.lastIndexOf("\\")); getDesktop().open(new File(newPath)); } }
使用 java I/O 实现一个简易的文件分割器功能
最新推荐文章于 2020-11-23 21:29:43 发布