java学习之IO文件分割

 package om.gh.homework;
import java.io.*;
/**
* 实现分割文件;
* @param file
*/
public class HomeWork {
/**
* @param src
* 要分割的文件路径
* @param n
* 每个文件的大小以mb为单位
* @param desc
* 分割的文件存放路径
* @throws FileNotFoundException
*/
public static void filesplit(File src, int mb, File desc)
throws FileNotFoundException {
// 判断文件路径
if (src.exists() && src.isFile() && desc.isDirectory()) {
int fileSize = mb * 1024 * 1024;
int n;
// 判断要分割文件的个数n;
if (src.length() % fileSize == 0)
n = (int) (src.length() / fileSize);
else
n = (int) (src.length() / fileSize) + 1;
try {
InputStream is = new FileInputStream(src);
BufferedInputStream bis = new BufferedInputStream(is);
for (int i = 0; i < n; i++) {// 循环写入每个文件;
byte[] b = new byte[fileSize];
String newfile = desc.getPath() + File.separator
+ src.getName()+"_"+ i + ".dat";
BufferedOutputStream bos = new BufferedOutputStream(//缓存流
new FileOutputStream(newfile));
int len = -1;
int count=0;
while ((len = bis.read(b)) != -1) {
bos.write(b,0,len);
count+=len;
bos.flush();
if(count>=fileSize)break;
}
bos.close();
}
bis.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new FileNotFoundException("文件不存在或者参数错误!");
}
} public static void main(String[] args) {
File src = new File("F:\\电影\\万万没想到.mp4");//要分割的目标文件
File desc = new File("f:\\视频\\");//分割完存放的路径
int mb = 500;// 每个文件大小,以Mb为单位;
System.out.println("开始分割...");
try {
filesplit(src, mb, desc);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("分割完成!");
}
}
 package om.gh.homework;
import java.io.*;
/**
* 把分割后的文件合并
*
* @author ganhang
*
*/
public class Homework2 {
/**
*
* @param desc
* 合成后的文件路径
* @param src
* 要合成的文件列表
*/
public static void merge(File desc, File... src) {
try {
String filename = src[0].getName().substring(0,
src[0].getName().lastIndexOf("_"));
File newfile = new File(desc.getPath() + File.separator + filename);
OutputStream os = new FileOutputStream(newfile);
BufferedOutputStream bos = new BufferedOutputStream(os);
for (int i = 0; i < src.length; i++) {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(src[i]));
byte[] b = new byte[1024 * 1024];
int len = -1;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
bis.close();
}
bos.close();
os.close();
System.out.println("合成成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File desc=new File("f:\\视频\\");
File [] src={
new File("f:\\视频\\万万没想到.mp4_0.dat"),
new File("f:\\视频\\万万没想到.mp4_1.dat"),
new File("f:\\视频\\万万没想到.mp4_2.dat"),
new File("f:\\视频\\万万没想到.mp4_3.dat")
};
System.out.println("开始合成...");
merge(desc,src);
}
}
上一篇:C#4.0 HTTP协议无法使用TLS1.2的问题


下一篇:Docker for windows10 配置阿里云镜像