/* * 小程序:切割和合并mp3文件 */
package com.michael.lin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;
public class Demo02 {
public static void main(String[] args) throws IOException{nifeMp3();mergeMp3();}
//1.切割mp3文件
public static void nifeMp3() throws IOException {
//1.定位要切割的文件
File mp3File = new File("c:\\music\\michael.mp3");
//2.定位切割文件存放位置
File partsFile = new File("c:\\music\\parts\\");
//3.定位输入通道
FileInputStream fileInputStream = new FileInputStream(mp3File);
byte[] buf = new byte[1024*1024];
int length = 0;
for(int i=0; (length=fileInputStream.read(buf))!=-1; i++){
File part = new File(partsFile, "part"+i+".mp3");
FileOutputStream fileOutputStream = new FileOutputStream(part);
fileOutputStream.write(buf,0,length);
fileOutputStream.close();}fileInputStream.close();
}
//2.合并mp3文件
public static void mergeMp3() throws IOException{
//1.定位要和并的文件的位置
File dir = new File("c:\\music\\parts\\");
//2.列出所有要合并的文件存入序列流中
Vectorvector = new Vector();
File[] files = dir.listFiles();
for(File file: files){
if(file.toString().endsWith(".mp3")){
FileInputStream fileInputStream = new FileInputStream(file);
vector.add(fileInputStream);
}
}
//将文件集合放入序列输入流中
Enumerationenumeration = vector.elements();
SequenceInputStream sequenceInputStream = new SequenceInputStream(enumeration);
//3.开始和合并文件
File michael = new File(dir,"michael.mp3");
FileOutputStream michaelOutput = new FileOutputStream(michael);
byte[] buf = new byte[1024];
int length = 0;
while((length=sequenceInputStream.read(buf))!=-1){
michaelOutput.write(buf,0,length);
}
}
sequenceInputStream.close();
michaelOutput.close();
}