需求: 把一首MP3切成n份,每份是1m,然后再合并起来。
public class Demo2 {
public static void main(String[] args) throws IOException {
// cutFile();
mergeFile();
}
//合并mp3文件
public static void mergeFile() throws IOException{
File dir= new File("f:\\music");
File[] files = dir.listFiles(); //获取到文件夹中的所有子文件
//创建一个Vector对象存储FileInputStream对象
Vector<FileInputStream> vector = new Vector<FileInputStream>();
//遍历数组,
for(int i = 0; i<files.length ; i++){
if(files[i].getName().endsWith(".mp3")){
vector.add(new FileInputStream(files[i]));
}
}
//创建一个序列流对象
SequenceInputStream inputStream = new SequenceInputStream(vector.elements());
//创建一个输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("f:\\晚风.mp3");
//边读边写
byte[] buf = new byte[1024];
int length = 0;
while((length = inputStream.read(buf))!=-1){
fileOutputStream.write(buf,0,length);
}
//关闭资源
fileOutputStream.close();
inputStream.close();
}
//切割mp3
public static void cutFile() throws IOException{
File file = new File("F:\\美女\\1.mp3");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buf = new byte[1024*1024];
int length = 0 ;
int count = 1;
while((length = fileInputStream.read(buf))!=-1){
//每读取一次,则生成一个文件
FileOutputStream fileOutputStream = new FileOutputStream("F:\\music\\part"+count+".mp3");
//把读取到的数据写出
fileOutputStream.write(buf,0,length);
count++;
//关闭资源
fileOutputStream.close();
}
//关闭资源
fileInputStream.close();
}
}