1.使用字节流拷贝图片
public class CopyPic {
public static void main(String[] args) {
//定义字节流
FileInputStream fis = null;
FileOutputStream fos = null;
try{
//初始化字节流
fis = new FileInputStream("C:\\1.png");
fos = new FileOutputStream("d:\\1.png");
//字节数组
byte[] buf = new byte[1024];
int len = 0;
//判断是否读到文件末尾只要判断返回值是否为-1
while((len = fis.read(buf)) != -1){
fos.write(buf, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
//分别关闭字节流
try{
if(fis != null)
fis.close();
}catch(IOException e){
e.printStackTrace();
}
try{
if(fos != null)
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}2.使用带缓冲的字节流拷贝MP3
public class CopyMP3 {
public static void main(String[] args) throws IOException {
//定义字节流
FileInputStream fis = null;
FileOutputStream fos = null;
//定义带缓冲的字节流
BufferedInputStream bufin = null;
BufferedOutputStream bufout = null;
try{
//初始化字节流
fis = new FileInputStream("c:\\再回首.mp3");
fos = new FileOutputStream("D:\\再回首.mp3");
//初始化带缓存的字节流
bufin = new BufferedInputStream(fis);
bufout = new BufferedOutputStream(fos);
//字节数组
byte[] buf = new byte[1024*8];
int len = 0;
while((len = bufin.read(buf)) != -1){
bufout.write(buf, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
//分别关闭带缓存的字节流
try{
if(bufin != null)
bufin.close();
}catch(IOException e){
e.printStackTrace();
}
try{
if(bufout != null)
bufout.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}3.模拟一个BufferedInputStream,实现read方法,将读取的一批字节缓存到一个字节数组中然后处理。
注意到InputStream类的read方法返回值是int而不是byte。为什么读取一个byte型返回值不是byte而是进行了提升成int型呢?
因为读取文件是,很可能读到连续8个1,这连续8个1的整数值是-1,但是又不是末尾,如果返回-1会使程序误认为读到末尾而结束。为了避免这种情况,所以将8位变成32位,将读到的8位二进制保留,前面添加24个0。如何在其前面补24个0呢?让这个字节数与255即可。而OutputStream的writer方法在内部将其后8位截取保留。
public class MyBufferedInputStream {
private InputStream in;
//数组指针
private int pos = 0;
//计数器
private int count = 0;
//字节数组
byte[] buf = new byte[1024];
public MyBufferedInputStream(InputStream in){
this.in = in;
}
//读一个字节
public int myRead() throws IOException{
//将读取到的一批字节放入数组中,然后一个字节一个字节的返回
/*
* 有可能读到连续8个1,即-1,此时一判断,会误认为读到结尾,读取结束。
* 为了避免这种情况,所以将返回值提升为int而不是byte。
* 在8个二进制前面全都补0,所以返回值要与255,即与0xff(16进制)
* */
//如果count为0,则向数组添加字节,并将指针设为0
if(count == 0){
count = in.read(buf);
pos = 0;
//如果count小于0,说明没有内容或者已读到结尾,返回-1
if(count < 0)
return -1;
}
//返回一个字节后,指针加一,count减一
count--;
return buf[pos++]&0xff;
}
public void myClose() throws IOException{
in.close();
}
}
本文详细介绍了使用字节流和缓冲字节流进行文件拷贝的方法,包括复制图片和MP3文件的具体实现。通过实例代码展示了如何使用FileInputStream和FileOutputStream进行基本文件操作,并通过BufferedInputStream和BufferedOutputStream提高读写效率。

760

被折叠的 条评论
为什么被折叠?



