文件字节输入、输出流 FileInputStream、FileOutputStream
文件字符输入、输出流 FileReader、FileWriter
缓冲流自带8kb缓冲区,提高原始字节流、字符流读写数据的性能
字节缓冲输入、输出流 BufferedInputStream、BufferedOutputStream
字符缓冲输入、输出流 BufferedReader、BufferedWriter
转换流 InputStreamReader、OutputStreamWrite
对象字节输入、输出流 ObjectInputStream、ObjectOutputStream
InputStreamReader、OutputStreamWriter
- FileInputStream fis = new FileInputStream("test.txt");
- InputStreamReader isr = new InputStreamReader(fis, "GBK");
- BufferedReader br = new BufferedReader(isr);
- String line;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
-
-
- FileOutputStream fos = new FileOutputStream("test.txt");
- OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
- BufferedWriter bw = new BufferedWriter(osw);
- bw.write("这是中文");
- bw.close();
ObjectOutputStream、ObjectInputStream
被序列化的对象,属性增加修饰符transient,可以忽略使此属性在序列化后为null(常用于敏感信息)
被序列化的对象,必须实现接口Serializable
- // 序列化
- Book book = new Book("name");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.txt"));
- objectOutputStream.writeObject(book);
- objectOutputStream.close();
-
- // 反序列化
- ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.txt"));
- Object o = objectInputStream.readObject();
- objectInputStream.close();
- System.out.println(o);
打印流:PrintStream(字节)、PrintWriter(字符)
- PrintStream printStream = new PrintStream("test.txt");
- printStream.println("test");
- printStream.flush();
改变输出语句的位置到文件
- PrintStream ps = new PrintStream("log.txt");
- System.setOut(ps);
- System.out.println("test"); // 现在不会输出到console,会出现在log.txt文件中
Properties类
- Properties properties = new Properties();
- properties.setProperty("key1", "value1");
- properties.store(new FileWriter("user.properties"), "备注信息");
commons-io框架(推荐使用)