Day10:JAVA IO上

Day10:JAVA IO上

流分类

按流向

输入流

输出流

按单位

字节流:可以传输任何数据,以字节来传输

字符流:只能传输文本数据,以字符来传输

按功能

节点流:具有实际传输数据的读写功能(也称为底层流)

过滤流:在节点流基础之上增强功能

字节流

父类为两个抽象类:

InputStream

void close()

void mark()

void markSupported()

void reset()

abstract int read()

int read(byte[] b)

int read(byte[] b,int off,int len) //偏移量off

OutputStream

void close()

void flush()

void write(byte[] b)

void write(byte[] b,int off,int len)

abstract void write(int b) //将指定的字节写入此输出流

FileInputStream

InputStream的实现类

构造方法有三个有参的:

FileInputStream(File file)

FileInputStream(String name) //name为文件路径

FileInputStream(FileDescriptor fdObj)

方法:

protected void finalize() //不会直接用;确保在不再引用文件输入流时调用其close方法

long skip(long n) //从输入流中跳过并丢弃n个字节的数据

读取

  1. 创建一个用于存放每次读取的字节的地方

  2. 当没读完就继续读

FileInputStream fis = new FileInputStream("D:\\a.txt");

单次读取

int data = 0;

while((data=fis.read())!=-1){

//做相关操作

}

一次读取多个字节

byte[] buf = new byte[1024];

int count = 0;

while((count=fis.read(buf))!=-1){

System.out.println(new String(buf,0,count));

}

fis.close();

FileOutputStream

构造方法:

FileOutputStream(String name) //没有name则创建,有则覆盖

FileOutputStream(String name,boolean append) //如果有name,选择是否在已有文件后追加内容

使用

FileOutputStream fos = new FileOutputStream("b.txt");

fos.write(97);

fos.write('a');

String data = "HellWorld!";

fos.write(data.getBytes());

fos.close();

实现文件复制

FileInputStream fis = new FileInputStream("D:\\a.txt");

FileOutputStream fos = new FileOutputStream("b.txt");

byte[] buf = new byte[1024];

int count = 0;

while((count=fis.read(buf))!=-1){

fos.write(buf,0,count);

}

fis.close();

fos.close();

字节缓冲流(过滤流)

比文件字节流效率高

BufferedInputStream //父类为FilterInputStream

BufferedOutputStream //父类为FilterOutputStream

  • 提高IO效率,减少访问磁盘的次数

  • 数据存储在缓冲区中,flush是将缓冲区中的内容写入文件中,也可以直接close

默认缓冲区大小为8k

使用:

BufferedInputStream bis = new BufferedInputStream(fis);

bis.read()

bis.read(buf)

BufferedOutputStream bos = new BufferedOutputStream(fos);

bos.write("HelloWorld".getBytes());

bos.flush();

注意:

关闭的时候只需要关闭缓冲流

bis.close();

bos.close();

对象流

也是属于过滤流的一种

序列化:写出

反序列化:读入

最重要的两个方法:

ObjectInputStream

Object readObject()

ObjectOutputStream

void writeObject(Object o)

  • 增强了缓冲区功能

  • 增强了读写8种基本数据类型和字符串功能

  • 增强了读写对象的功能

注意

  1. 要序列化的对象必须实现Serializable接口

  2. EOFException:已经读完了你还读

  3. private static final long serialVersionUID:序列化版本号ID,保证序列化的类和反序列化的类是同一个类

  4. 序列化类中的对象属性也要实现Serializable接口

  5. transient修饰的属性可以不被序列化

  6. 静态属性也不能被序列化

  7. 序列化多个对象,用集合装载多个对象就行

跟流相关的代码通常要不用trycatch包围要不主动抛出

字符流前瞻

两个父类(抽象类)

Reader、Writer

方法还是熟悉的read和write

文件字符流

FileReader

父类为InputStreamReader,InputStreamReader的父类是Reader

FileWriter

父类为OutputStreamWriter,OutputStreamWriter的父类是Writer

建议每次写入也flush一下

posted @ 2021-06-03 23:10  Layman52  阅读(85)  评论(0)    收藏  举报