Day20
一、内存流(ByteArrayOutputStream父类是OutputStream、ByteArrayInputStream父类是InputStream)
- 常规方法:toByteArray();toString(),close()流关闭无效,因为无法关闭内存(了解即可)
二、打印流(字节打印PrintStream、字符打印PrintWriter)(了解即可)
三、随机流(RandomAccessFile)
- 构造方法: public RandomAccessFile(String name,String mode)第一个参数传递的是路径,第二个参数传递的是模式(“r”,“rw”,“rws”,“rwd”)
- 常规的方法:seek(long pos)设置指针的偏移量;getFilePointer()获取指针的偏移量;read()读write(int b)写
四、Properties(父类是Hashtable,表示一个持久的属性集,可以当Map使用)《重点》
1、构造方法:public Properties()
2、常规方法:
- public void load(InputStream inStream):加载流的资源的方法;
- public String getProperty(String key):获取值的方法;
- public Object setProperty(String key,String value):设置值;
- public void store(OutputStream out,String comments):把修改的数据结合流对象放入到文件里;
- public Set stringPropertyNames():获取到所有的键的方法;
3、遍历的两种方式:
- 获取到所有的键stringPropertyNames()然后返回的是一个set集合,使用set集合遍历;
- 使用entrySet()然后返回的是一个Map.Entry;
开发中使用最多的是读取配置文件
4、步骤:实例化对象Properties–>使用方法加载入流load(InputStream)–>使用键值对获取数据getProperty(String key)
package com.yxlim.day20;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* 输入流和输出流只能对应流操作完间隔出现
*/
public class Test2 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("1.properties");
Properties p = new Properties();
p.load(fis);
System.out.println(p.getProperty("plan2"));
/* FileOutputStream fos = new FileOutputStream("1.properties");
p.setProperty("plan1", "C");
p.store(fos, "");
fos.close();*/
fis.close();
}
}
五、标准的输入输出(in–>InputStream、out–>PrintSream)
六、IO流异常的处理
- 一定要进行捕获,不要抛给jvm,但可以抛给方法
- 在finally关闭资源一定要进行非null验证