InputStream OutputStream
1. 构造方法
FileInputStream(String name) 抛IOException
FileOutputStream(String name) 抛IOException如果该目录下已有同名文件,将被覆盖
FileOutputStream(String name, boolean append) 抛IOException 若append为true文件续写
2. 常用方法
InputStream:
Int available()//返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。
abstract Int read();//读取下一个字节,没有数据返回-1。抛IOException
Int read(byte [] b);//将字节读入数组,没有数据返回-1。抛IOException
Int read(byte[] b, int off, int len)// 将字节读入数组的某一部分。抛IOException
close()//关闭该流并释放与之关联的所有资源。抛IOException
OutputStream:
write(byte [] b) // 写入字节数组。抛IOException
write(byte [] b, int off, int len) // 写入字节数组的某一部分。抛IOException
write(int b)//写入单个字节。抛IOException
flush()//刷新该流的缓冲。抛IOException
close()//关闭该流并释放与之关联的所有资源。抛IOException
3. BufferedInputStream BufferedOutputStream
4. 例:
/*
演示mp3的复制。通过缓冲区。
BufferedOutputStream
BufferedInputStream
*/
import java.io.*;
class CopyMp3
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
copy_2();
long end = System.currentTimeMillis();
System.out.println((end-start)+"毫秒");
}
//通过字节流的缓冲区完成复制。
public static void copy_1()throws IOException
{
BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("c:\\0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\1.mp3"));
int by = 0;
while((by=bufis.read())!=-1)
{
bufos.write(by);
}
bufos.close();
bufis.close();
}
}
5. BufferedInputStream原理:
import java.io.*;
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024*4];
private int pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
//一次读一个字节,从缓冲区(字节数组)获取。
public int myRead()throws IOException
{
//通过in对象读取硬盘上数据,并存储buf中。
if(count==0)
{
count = in.read(buf);
if(count<0)
return -1;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
else if(count>0)
{
byte b = buf[pos];
count--;
pos++;
return b&0xff;
}
return -1;
}
public void myClose()throws IOException
{
in.close();
}
}
********************
结论:
字节流的读一个字节的read方法为什么返回值类型不是byte,而是int。
因为有可能会读到连续8个二进制1的情况,8个二进制1对应的十进制是-1.
那么就会数据还没有读完,就结束的情况。因为我们判断读取结束是通过结尾标记-1来确定的。
所以,为了避免这种情况将读到的字节进行int类型的提升。
并在保留原字节数据的情况前面了补了24个0,变成了int类型的数值。
而在写入数据时,只写该int类型数据的最低8位。
********************
---------------------------------------------------------------------
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |