字节流读文件
工程结构
try {
//一个汉字占用两个字节
String str="我我";
byte[] b=str.getBytes();
//创建字节输入流,用于读取当前目录下的文件
InputStream is=new FileInputStream("source\\test.text");
//创建字节输出流
OutputStream os=new FileOutputStream("target\\testTarget.text");
//获取当前时间
long start=System.currentTimeMillis();
int len;//定义len保存每次读取的字节数
while((len=is.read())!=-1){
os.write(len);
}
os.close();
is.close();
//结束时间
long end=System.currentTimeMillis();
System.out.println("用时"+(end-start)+"毫秒");
is.close();
os.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("文件没有找到;");
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
文件拷贝
第一种方法,一个字节一个字节的读取,速度非常慢,下面我将一个音乐文件复制到另一个文件中
try {
InputStream in=in=new FileInputStream("source\\三角题 - 二珂.mp3");//定义字节输入流;
OutputStream ou=new FileOutputStream("target\\三角题 - 二珂.mp3");//定义字节输出流
//byte[] b=new byte[1024];//定义一个byte类型数组,用作字节缓冲区
int len;//定义长度
long start=System.currentTimeMillis();//定义开始时间
while((len=in.read())!=-1){
ou.write(len);
}
long end=System.currentTimeMillis();//定义结束时间
System.out.println("使用字节缓冲区拷贝用时"+(end-start)+"毫秒");
in.close();//关闭输入流
ou.close();//关闭输出流
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("文件没有找到");
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
高效率复制(局部代码段)
byte[] b=new byte[1024];//定义一个byte类型数组,用作字节流缓冲区
int len;//定义长度
while((len=in.read(b))!=-1){
ou.write(b);
}
同样的一首歌曲,复制时间天差地别
第三种方法是:使用IO包中提供的字节缓冲流BufferedInputStream和BufferedOutputStream
try {
//创建带缓冲区的字节输入流
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("source\\三角题 - 二珂.mp3"));
//创建带缓冲区的字节输出流
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("target\\三角题 - 二珂.mp3"));
long start=System.currentTimeMillis();
int len;
while((len=bis.read())!=-1){
bos.write(len);
}
long end=System.currentTimeMillis();
System.out.println("时间"+(end-start)+"毫秒");
bis.close();
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}