Java基础 Day23
一、字符缓冲流
字符缓冲流在源代码中内置了字符数组,可以提高读写效率
1、构造方法
BufferedReader(Reader reader) | 对传入的字符输入流进行包装 |
BufferedWriter(Writer writer) | 对传入的字符输出流进行包装 |
注意: 缓冲流不具备读写功能, 它们只是对普通的流对象进行包装
真正和文件建立关联的, 还是普通的流对象
2、特有方法
(1)BufferedReader
public String readLine() |
(2)BufferedWriter
public void newLine() |
二、转换流
1、作用
按照指定的字符编码进行读写操作
将字节流转换成字符流进行操作
2、构造方法
InputStreamReader (InputStream in, String charsetName) | |
OutputStreamReader (OutputStream out, String charsetName) |
三、序列化流
可以在流中,以字节的形式直接读写对象
1、构造方法
public ObjectInputStream(InputStream in) | |
public ObjectOutputStream(OutputStream out) |
2、成员方法
(1)ObjectInputStream
Object readObject() |
注意:readObject方法读到末尾会抛出EOFException异常
(2)ObjectOutputStream
void writeObject(Object obj) |
3、注意事项
(1)类需要实现Serializable接口才能序列化
(2)使用transient关键字修饰成员变量,该成员变量不会序列化
(3)实现Serializable接口,类会有一个serialVersionUID(版本号),最好手动编写
四、打印流
1、简介
打印流可以实现方便、高效的打印数据到文件中去,并且可以指定字符编码
可以实现打印什么数据就是什么数据,原样打印
System.out 就是一个PrintStream 流的对象,关联到控制台
2、PrintStream 流
public PrintStream (OutputStream os) | |
public PrintStream (File f, String csn) | |
public PrintStream (String filepath, String csn) | |
public void print\println(Xxx xx) |
3、PrintWriter 字符打印流
public PrintWriter (OutputStream os) | |
public PrintWriter (Writer w) | |
public PrintWriter (File f) | |
public PrintWriter (String filepath) | |
public void print\println(Xxx xx) |
五、Properties 集合
本质就是一个Map集合,常用于加载配置文件
构造方法用空参构造
1、Properties 作为集合的使用
Object setProperty(String key, String value) | |
String getProperty(String key) | |
Set<String> stringPropertyNames() |
2、Properties 和 IO 有关的方法
void load(InputStream inStream) | |
void load(Reader reader) | |
void store(OutputStream out, String comments) | |
void store(Writer writer, String comments) |
public class PropertiesDemo {public static void main(String[] args) throws IOException {Properties prop = new Properties();prop.setProperty("username", "Tom");prop.setProperty("password", "123456");System.out.println(prop.getProperty("username"));System.out.println(prop.getProperty("password"));// 注意后缀名用 .propertiesFileWriter fw = new FileWriter("./day23/src/config.properties");prop.store(fw, "This is a test");fw.close();Properties prop2 = new Properties();FileReader fr = new FileReader("./day23/src/config.properties");prop2.load(fr);fr.close();System.out.println(prop2);}
}控制台输出:
Tom
123456
{password=123456, username=Tom}config.properties 文件内容:
#This is a test
#Wed May 28 22:48:32 GMT+08:00 2025
password=123456
username=Tom