一、需求
将一首mp3切割后再合并。
二、代码
public class Main
{
public static void main(String[] args) throws IOException
{
spilt();
merge();
}
static void spilt() throws IOException
{
//源文件
File file = new File("/Users/yao/Music/","生活不止眼前的苟且.mp3");
//目标文件夹
File dir = new File("/Users/yao/Music/");
//建立数据通道
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲数组读取
byte[] buff = new byte[1024*1024]; //切割后,每个文件大小为1M
int length = 0;
for(int i = 1 ; (length = fileInputStream.read(buff))!=-1 ; i++)
{
FileOutputStream fileOutputStream = new FileOutputStream(new File(dir,file.getName()+"_part"+i+"_.mp3"));
fileOutputStream.write(buff, 0, length);
fileOutputStream.close();
}
fileInputStream.close();
}
static void merge() throws IOException
{
//找到目标文件
File dir = new File("/Users/yao/Music/");
File[] files = dir.listFiles();
//通过目标文件夹找到所有的MP3文件,然后把所有的_.mp3文件添加到vector中。
Vector<FileInputStream> vector = new Vector<FileInputStream>();
for(File f : files)
{
if(f.getName().endsWith("_.mp3"))
{
vector.add(new FileInputStream(f));
}
}
//通过Vector获取迭代器
Enumeration<FileInputStream> e = vector.elements();
//创建序列流
SequenceInputStream inputStream = new SequenceInputStream(e);
//建立文件的输出通道
FileOutputStream fileOutputStream = new FileOutputStream("/Users/yao/Music/合并.mp3");
//建立缓冲数组读取文件
byte[] buf = new byte[1024];
int length = 0 ;
while((length = inputStream.read(buf))!=-1){
fileOutputStream.write(buf,0,length);
}
//关闭资源
fileOutputStream.close();
inputStream.close();
}
}