JavaIO流实例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyMp3 {

public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 要复制的文件的位置
* File.separator是File类的静态变量="\",为了程序在window系统和linux系统的兼容,使用这种方式
* 代替"\"移植性更好
* s.h.e.mp3要复制的文件
*/
//String filename = "D:"+File.separator+"music"+File.separator+"s.h.e.mp3";
//System.out.println(filename);
File f = new File("D:"+File.separator+"music"+File.separator+"s.h.e.mp3");
/*
* she.mp3复制后的文件
*/
File out = new File("D:"+File.separator+"she.mp3");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//文件输入流
fis = new FileInputStream(f);
//文件输出流
fos = new FileOutputStream(out);

//获得文件的长度,注意文件过大时候可能会出现int越界错误
@SuppressWarnings("unused")
int len = fis.available();

byte[] b = new byte[1024];//定义一个byte数组,大小为1k
@SuppressWarnings("unused")
int index=0;

//循环读取inputstream流中的数据,直到读到文件末尾,每次读取1k,防止因文件过大造成
//对内存的消耗过大
while((index=fis.read(b))!=-1){
//将byte数组中的数据写到输出流中
fos.write(b);
}
// byte[] b = new byte[fis.available()];


} catch (FileNotFoundException e) {
System.out.println("文件未找到");
e.printStackTrace();
}catch(IOException e){
System.out.println("读取错误!");
}
finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("流关闭失败!");
e.printStackTrace();
}

}
}

}

相关文档
最新文档