- import java.io.*;
- public class SplitFile {
- public static void main(String[] args) {
- splitFile("F:\\陈奕迅 - 十年.mp3", 1);
- }
-
- /**
- * @param fileName:文件名
- * @param length:要分割的长度,以M为单位
- */
- static void splitFile(String fileName, long length) {
- final long SIZE = length * 1024 *1024;
- int count = 1;
- int c;
- long len = 0;
- BufferedInputStream bufInS = null;
- BufferedOutputStream bufOutS = null;
-
- File file = new File(fileName);
- File fileAbs = file.getAbsoluteFile(); //获取绝对路径
- String parent = fileAbs.getParent(); //获取要分割文件所在目录
-
- try {
- bufInS = new BufferedInputStream(new FileInputStream(fileAbs)); //创建要分割文件的输入流
- bufOutS = new BufferedOutputStream(new FileOutputStream(parent + count + ".part")); //创建分割后的文件第一部分
-
- while ((c = bufInS.read()) != -1) {
- len++;
- if (len > SIZE) { //前一部分文件写满,重新创建一个文件
- len = 0;
- count++;
- bufOutS.close(); //关闭前一部分文件的输出流
- bufOutS = new BufferedOutputStream(new FileOutputStream(parent + count + ".part")); //创建新文件的输出流
- }
- bufOutS.write(c); //给文件中写内容
- }
- } catch (FileNotFoundException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (bufInS != null) {
- bufInS.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- if (bufOutS != null) {
- bufOutS.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
- }
复制代码
简单的写了一下 |