字节流 :操作图片等数据用到字节流
字符流使用到的数组是char[] 字节流使用到的是Byte[]
字节流基类:InputStream OutputStream
1 字节读取流
拷贝图片
public static void main(String []args){
InputStream is =null;
OutputStream os =null;
try{
is =new FileInputStream("C:\\2.jpg");
os =new FileOutputStream("D:\\2.jpg");
byte []buf =new byte[10000000];
for(int len=0;(len=is.read(buf))!=-1;){
os.write(buf,0,len);
System.out.println(len+"");
}
}
catch(IOException e){
System.out.println("读写错误");
}
finally{
try{
if(is!=null)
is.close();
}
catch(IOException e){
System.out.println("读取流关闭失败");
}
finally{
try{
if(os!=null)
os.close();
}
catch(IOException e){
System.out.println("写入流关闭失败");
}
}
}
}
这里特别的探讨下len=is.read(buf) 在for循环中 buf的长度为初始化数组的长度,没执行一次for循环,就read buf长度的字节。下一次循环buf 数组清空
2 字节缓冲流
public static void main(String...args)throws IOException{
BufferedInputStream is = new BufferedInputStream (new FileInputStream("C:\\1.mp3"));
<span style="white-space:pre"> </span>BufferedOutputStream os = new BufferedOutputStream (new FileOutputStream("D:\\1.mp3"));
<span style="white-space:pre"> </span>for(int by = 0;(by=is.read())!=-1;){
<span style="white-space:pre"> </span>os.write(by);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>is.close();
<span style="white-space:pre"> </span>os.close();
}