您的位置:首页 > Web前端

IO流-BufferedInputStream输入缓冲流

2017-09-20 01:20 253 查看

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中的内容读取,输出在控制台

 * @author Administrator

 *

 */

public class TestFileReader {

public static void main(String[] args) {

//声明输入流对象

Reader fr = null;

try {

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

fr = new FileReader("E:/others/a/hello2.txt");

//声明char数组,用于存储读取的内容

char[] buffer =
new char
[10];

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

int len = 0;

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

//将读取到的内容
char数组中的,转换成字符串

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

System.out.println(str);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源...

}

}

}

1.6. FileWriter字符流写文件

“今天吃了10个饺子”写出到E:/others/a/hello6.txt中

/**

 * “今天吃了10个饺子”写出到E:/others/a/hello6.txt

 * void write(String str)

          写入字符串。  

   字符串---char[]字符数组    toCharArray()

 char[]---字符串      new String(char[] buffer)   

 new String(char[] buffer,int offset
int len);  从数组buffer中索引为offset的位置开始,截取

 len 个字符
转换成字符串

   字符串---byte[]字节数组    getBytes()

 byte[]---字符串   new String(byte[]buffer)

 new String(byte[] buffer,int offset,int len);
解释同上

 笔试题:
字符串如何转换成字节数组,字节数组如何转换成字符串

     字符串如何转换成字符数组,字符数组如何转换成字符串

 * @author Administrator

 *

 */

public class TestFileWriter {

public static void main(String[] args) {

Writer fw = null;

try {

fw = new FileWriter("E:/others/a/hello6.txt");

//fw.write("今天吃了10个饺子!");

char[] arr =
"今天吃了10个饺子!".toCharArray();

fw.write(arr);

fw.flush();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

API:

append

write(String s);

1.7. 字符流拷贝文件

将E:/others/a/hello2.txt拷贝到D:hello.txt

FileReader读取,读取的过程中,用FileWriter写出 ,边读,边写

/**

 * 将E:/others/a/hello2.txt拷贝到D:hello.txt

 * @author Administrator

 *

 */

public class TestFileReaderAndWriter {

public static void main(String[] args) {

//声明输入流对象,声明输出流对象

Reader rd = null;

Writer wt = null;

try {

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

rd = new FileReader("E:/others/a/hello2.txt");

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

wt = new FileWriter("D:/hello.txt");

char[] buffer  =
new char
[10];

int len = 0;

System.out.println("hello2.txt总的字节数(文件的大小):"+new FileInputStream("E:/others/a/hello2.txt").available());

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

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

//必须用这个,读多少,写多少

wt.write(buffer, 0, len);

wt.flush();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

1.8. BufferedWriter写入缓冲流

今天吃了10个饺子”写出到E:/others/a/hello6.txt中

/**

 * 将2行
“今天吃了10个饺子”写出到E:/others/a/hello6.txt中,一行一句

 * void write(String str)

 * BufferedWriter(Writer out)

          创建一个使用默认大小输出缓冲区的缓冲字符输出流。

   newLine();  换行

 * @author Administrator

 *

 */

public class TestBufferedWriter {

public static void main(String[] args) {

BufferedWriter bw = null;

try {

bw =new BufferedWriter(new FileWriter("E:/others/a/hello6.txt"));

bw.write("今天吃了10个饺子");

bw.newLine(); //换行  “\r\n”

bw.write("今天吃了10个饺子");

bw.flush();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

1.9. BufferedReader读取缓冲流

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

/**

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

 * BufferedReader(Reader in)

          创建一个使用默认大小输入缓冲区的缓冲字符输入流。

   String readLine()  

          读取一个文本行。  按行读取,返回的是一个字符串,如果读到的是null,表示读到文件末尾
      

 * @author Administrator

 *

 */

public class TestBufferedReader {

public static void main(String[] args) {

//声明输入流对象

BufferedReader br = null;

try {

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

br = new BufferedReader(new FileReader("E:/others/a/hello2.txt"));

//声明String变量,用来接收读取到内容

String data = new String();

while((data=br.readLine())!=null){

System.out.println(data);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源...

}

}

}

1.10. 字符缓冲流拷贝文件(边读编写)

将E:/others/a/hello2.txt拷贝到D:hello.txt

/**

 * 将E:/others/a/hello2.txt拷贝到D:hello.txt

 * 简化代码

 * @author Administrator

 *

 */

public class TestBufferedReaderAndWriter02 {

public static void main(String[] args) {

//声明输入流对象,声明输出流对象

BufferedReader rd = null;

BufferedWriter wt = null;

try {

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

rd = new BufferedReader(new FileReader("E:/others/a/hello2.txt"));

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

wt =new BufferedWriter(new FileWriter("D:/hello.txt"));

String data = new String();

while((data=rd.readLine())!=null){

wt.write(data);

wt.newLine();

wt.flush();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

1.11. ByteArrayOutputStream(了解)

使用字节输出流将字节数组(字符串)写到内存中(目的地,存储介质)

package com.njwb.bytearraystream.d0511;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

/**

 * ByteArrayOutputStream()

    创建一个新的 byte
数组输出流。 这个输出流对象构造,没有参数可传,没有具体的目标文件可以存储内容,

    内容写到内存中

    输出流转换成byte[]数组
toByteArray()方法

 * @author Administrator

 *

 */

public class TestByteArrayOutputStream {

public static void main(String[] args) {

String str = "今天太阳不太好";

//构建输出流对象

ByteArrayOutputStream bos = new ByteArrayOutputStream();

try {

//输出流将数据写入内存中

bos.write(str.getBytes());

bos.flush();

//将输出流转换成byte数组,打印输出

byte[] data = bos.toByteArray();

System.out.println(new String(data));

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

为什么要有ByteArrayOutputStream?字节数组不是已经能存放文件了吗?

l 数组长度无法改变,可以把ByteArrayOutputStream看做是数组和ArrayList。

l 数据除了输出到文件,还会输出到显卡、网卡、声卡、打印机,将来会用到。

1.12. ByteArrayInputStream(了解)

通过字节输入流读取内存(存储介质)中的一个字节数组(字符串)

package com.njwb.bytearraystream.d0511;

import java.io.ByteArrayInputStream;

import java.io.IOException;

/**

 * ByteArrayInputStream(byte[] buf)

          创建一个 ByteArrayInputStream,使用
buf 作为其缓冲区数组。

          通过字节输入流读取内存(存储介质)中的一个字节数组

    new FileInputStream("E:/others/a.txt");

    

    File file = new File("E:/others/a.txt");

    new FileInputStream(file);

      将字节数组转换成输入流对象
,利用的构造

 * @author Administrator

 *

 */

public class TestByteArrayInputStream {

public static void main(String[] args) {

String str = "今天早上天气不太好";

byte[] arr = str.getBytes();

//将字节数组转换成输入流对象

ByteArrayInputStream bis = new ByteArrayInputStream(arr);

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

byte[]buffer =
new byte
[10];

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

int len =0;

try {

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

System.out.println(new String(buffer,0,len));

}

} catch (IOException e) {

e.printStackTrace();

}finally{

//关闭资源

}

}

}

1.13. DataInputStream数据输入流(读取二进制文件)DataOutputStream数据输出流

DataOutputStream类可以按照平台无关的方式向流中写入基本数据类型的数据,如int,float,long ,double,boolean,char,utf等。

DataInputStream 类可以按照与平台无关的方式从流中读取基本数据类型的数据,如int,float,long,double,boolean,char,utf-8等。

举例:各种类型先写入文件,再读出

/**

 * DataInputStream,DataOutputStream
数据输入字节流,输出输出字节流用法和前面的FileInputStream,FileOutputStream

 * 相同,但是有一些特殊的用法 ,可以读取,写出一些基本数据类型

 * 将int 10,double 12.33d,float 12.56f,boolean false,UTF-String
"今天吃了10个包子",char '男',

 * long 1000L

 * 写出到“E:/others/a/hello7.txt”中,再读取出来,输出在控制台,一行一个

 * DataOutputStream(OutputStream out)

          创建一个新的数据输出流,将数据写入指定基础输出流。

 * @author Administrator

 *

 */

public class TestDataInputStreamAndOutputStream {

public static void main(String[] args) {

//声明输入,输出流对象

DataInputStream dis = null;

DataOutputStream dos =
null
;

try {

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

dos  =new DataOutputStream(new FileOutputStream("E:/others/a/hello7.txt"));

dos.writeInt(10);

dos.writeDouble(12.33d);

dos.writeFloat(12.56f);

dos.writeBoolean(false);

dos.writeUTF("今天吃了10个包子");

dos.writeChar('男');

dos.writeLong(1000L);

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

dis = new DataInputStream(new FileInputStream("E:/others/a/hello7.txt"));

//注意:读取的顺序和写入的顺序一致

System.out.println(dis.readInt());

System.out.println(dis.readDouble());

System.out.println(dis.readFloat());

System.out.println(dis.readBoolean());

System.out.println(dis.readUTF());

System.out.println(dis.readChar());

System.out.println(dis.readLong());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(null!=dis){

try {

dis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(null!=dos){

try {

dos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

1.14. ObjectInputStream和ObjectOutputStream 序列化和反序列化

使用序列化保存对象信息,使用反序列化获取对象信息

序列化步骤:1.要序列化的类User实现接口Serializable

2.创建一个对象输出流ObjectOutputStream,可以包装其他类型的输出流FileOutputStream

3.通过对象输出流的writeObject()方法写对象,也就是输出可序列化对象

反序列化步骤: 1.创建一个对象输入流ObjectInputStream ,可以包装其他类型的输入流FileInputStream

2.通过对象输入流readObject()方法读对象,解析读出的对象的属性信息

举例:user对象

总结:

import java.io.Serializable;

/**

 * 如果要序列化的类User,没有实现Serializable接口,就会爆发

 * java.io.NotSerializableException: com.njwb.serializable.User

 * @author Administrator

 *

 */

@SuppressWarnings("serial")

public class User
implements Serializable {

private String
name; //名字

private int age;
//年龄

private String
sex; //性别

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public User(String name,
int age, String sex) {

super();

this.name = name;

this.age = age;

this.sex = sex;

}

public User() {

}

}

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

/**

 * ObjectOutputStream(OutputStream out)

          创建写入指定 OutputStream
的 ObjectOutputStream。

   ObjectInputStream(InputStream in)

          创建从指定 InputStream
读取的 ObjectInputStream。   

    如果是一组对象
,比方5个User对象,如何序列化 ,思路:将5个对象存储到集合里,ArrayList
,

    writeObject(list)  List<User>list = ois.readObject();  遍历list集合,输出每个对象的属性信息
 

 * @author Administrator

 *

 */

public class TestUser {

public static void main(String[] args) {

//声明文件对象 既是目标文件,也是源文件

File file = new File("E:/others/a/hello8.txt");

User u = new User("张三",18,"男");

//将对象存储到文件中  序列化

//声明输出流对象

ObjectOutputStream oos = null;

//声明输入流对象 将对象从文件中解析出来  反序列化

ObjectInputStream ois = null;

try {

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

oos = new ObjectOutputStream(new FileOutputStream(file));

//写出

oos.writeObject(u);

oos.flush();

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

ois = new ObjectInputStream(new FileInputStream(file));

//读取

User u2 = (User)ois.readObject();

//解析读取的对象的属性信息

System.out.println("姓名:"+u2.getName()+",年龄:"+u2.getAge()+",性别:"+u2.getSex());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

}

 

 

 

 

 

1.15. 流的总结

字节流

InputStream

FileInputStream 文件输入字节流

BufferedInputStream 缓冲输入字节流

DataInputStream  数据输入字节流  ,有一些特殊的用法  readInt() readDouble()…. ReadUTF()….

反序列化 ObjectInputStream ois   readObject()

OutputStream

FileOutputStream 文件输出字节流

BufferedOutputStream 缓冲输出字节流flush的话必须写

DataOutputStream 数据输出字节流  ,有一些特殊的用法  writeInt   writeDouble …writeUTF()

序列化 ObjectOutputStream  writeObject()

字符流

FileReader  文件输入字符流

FileWriter   文件输出字符流

  Write(String str) 可以直接写字符串  

BufferedReader  缓冲字符输入流  readLine() 按行读取

BufferedWriter 缓冲字符输出流   write(String str) 写字符串   newline() 换行

解决中文乱码  InputStreamReader(InputStream in 其他的流对象,String charsetName 编码格式 ) ,文件的保存的编码格式,必须和程序中一致。

文件ANSI----程序中gbk    文件中UTF-8  ----程序中UTF-8

1.16. 字符集:

常见的字符集,了解

    (1)ASCII  ---美国信息互换标准码

                      共128个字符

    (2)ISO-8859-1 西欧字符码  又叫Latin-1

                      对ASCII兼容

    (3)GB2312字符编码-------一共收录了7445个字符,包括6763个汉字和682个其他字符 简体中文

    (4)GBK字符编码 简体中文和繁体中文

                        共收录了21886个字符,汉字、图形符号。。。。

    (5)Unicode

                     收录了全世界所有语言的字符

    (6)UTF-8   支持中文 ,多个国家

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐