IO流-BufferedInputStream输入缓冲流

1. IO流

1.1. BufferedInputStream输入缓冲流

怎么做?

举例—读取文件数据

/**

 * BufferedInputStream(InputStream in)  需要传入其他的流对象

          创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。

  " Buffered"字样的都是缓冲流,都是为了提高其他流的效率,缓冲输出流,必须强制刷新 flush(),将缓冲区的数据强制输出

  E:/others/a/hello2.txt ,将其内容读取输出在控制台

 * @author Administrator

 *

 */

public class TestBufferedInputStream {

public static void main(String[] args) {

//声明输入流对象

BufferedInputStream bis = null;

try {

//建立输入流和源文件之间的联系

bis = new BufferedInputStream(new FileInputStream("E:/others/a/hello2.txt"));

//声明byte[]用于存储读取的内容

byte[] buffer  =new byte[30];

//声明int变量用于存储实际读取的字节数

int len = 0;

while(-1!=(len=bis.read(buffer))){

System.out.println("len="+len);

String str = new String(buffer,0,len);

System.out.println(str);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(null!=bis){

try {

bis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

有什么意义?

自带8M缓冲区

特性:输入、缓冲、字节、文件

1.2. BufferedOutputStream输出缓冲流

怎么做?

举例

/**

 * 缓冲输出流

 * 今天吃了10个包子! 写出到E:/others/a/hello4.txt

 * BufferedOutputStream(OutputStream out)

          创建一个新的缓冲输出流,以将数据写入指定的底层输出流。

* 今天吃了10个包子写出到E:/others/helloworld.txt中  

 * 1void write(byte[] b) 固定的数据写出到目标文件 ,这个可以用,第2个也可以用

           b.length 个字节从指定 byte 数组写入此文件输出流中。

  2  void write(byte[] b, int off, int len) 2个方法 复制文件的时候,读多少,写多少 ,必须用第2个方法

          将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。

          len>=0 而且 len<=b.length-off

  3 void write(int b)  一次只能写1个整数  ,只能用来写字母,符号,已知ASCII码值的字符,汉字对应的整数值不知道,无法用该方法写出去

          将指定字节写入此文件输出流。

 * @author Administrator

 *

 */

public class TestBufferedOutputStream {

public static void main(String[] args) {

//声明输出流对象

BufferedOutputStream bos = null;

try {

//建立输出流和目标文件之间的联系

bos = new BufferedOutputStream(new FileOutputStream("E:/others/a/hello4.txt"));

//将数据转换成byte[]数组

byte[] data = "今天吃了10个包子!".getBytes();

//写出

//bos.write(data);

//2个等价

bos.write(data, 0, data.length);

//刷新

bos.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(null!=bos){

try {

//close()方法调用的时候,自动调用flush()方法

bos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

特性:输出、缓冲、字节、文件

1.3. 字节流拷贝文件

拷贝文本,拷贝图片

封装该类为FileUtil,拷贝图片。

练习

l 拷贝目录A下的所有文件夹到目录B

l 拷贝目录A下的所有文件和文件夹到目录B

1.4. 字符流和字节流的区别

l stream结尾都是字节流,reader和writer结尾都是字符流

l 字节流可以读取所有文件,字符流只能用于读取文本文件。

l 一个是按字节读写,一个是按字符。

l 读写文件,与内容无关时,一般用字节流。

1.5. FileReader字符流读文件

必须理解和FileInputStream的区别

E:/others/a/hello2.txt中的内容读取,输出在控制台

/**

 * E:/others/a/hello2.txt中的内容读取,输出在控制台

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值