IO转换流

转换流提供了字节流与字符流之间的转换

  • 字节流中的数据都是字符时,转成字符流操作更高效。
  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

image.png

  • InputStreamReader:将一个字节的输入流转换为字符的输入流
  • 解码:字节、字节数组 —->字符数组、字符串

  • OutputStreamWriter:将一个字符的输出流转换为字节的输出流

  • 编码:字符数组、字符串 —-> 字节、字节数组

代码实现:

  1. @Test
  2. public void test2() throws Exception {
  3. //1.造文件、造流
  4. File file1 = new File("dbcp.txt");
  5. File file2 = new File("dbcp_gbk.txt");
  6. FileInputStream fis = new FileInputStream(file1);
  7. FileOutputStream fos = new FileOutputStream(file2);
  8. //第二个参数指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
  9. InputStreamReader isr = new InputStreamReader(fis,"utf-8");
  10. OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
  11. //2.读写过程
  12. char[] cbuf = new char[20];
  13. int len;
  14. while((len = isr.read(cbuf)) != -1){
  15. osw.write(cbuf,0,len);
  16. }
  17. //3.关闭资源
  18. isr.close();
  19. osw.close();
  20. }

对象流

对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
(但其实,后面我们都是用json来做这件事情的)

  • ObjectOutputStream:将内存中的对象变成存储中的文件、再通过网络传输出去
  • ObjectInputStream:将存储中的文件反序列化成内存中的对象

序列化

  1. @Test
  2. public void testObjectOutputStream(){
  3. ObjectOutputStream oos = null;
  4. try {
  5. //1.
  6. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
  7. //2.
  8. oos.writeObject(new String("我爱北京天安门"));
  9. oos.flush();//刷新操作
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. } finally {
  13. if(oos != null){
  14. //3.
  15. try {
  16. oos.close();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. }

反序列化

  1. @Test
  2. public void testObjectInputStream(){
  3. ObjectInputStream ois = null;
  4. try {
  5. ois = new ObjectInputStream(new FileInputStream("object.dat"));
  6. Object obj = ois.readObject();
  7. String str = (String) obj;
  8. System.out.println(str);
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. } catch (ClassNotFoundException e) {
  12. e.printStackTrace();
  13. } finally {
  14. if(ois != null){
  15. try {
  16. ois.close();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. }

当序列化的时候是一个对象时:

image.png

  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
  • transient:将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会被序列化。

NIO

NIO是java从1.4版本以后引入的新的IO API。

  • NIO支持面向缓冲区的(IO是面向流的)、基于 通道的IO操作。
  • NIO将以更加高效的方式、功能更强大进行文件的读写操作。
  • Path替换原有的File类。

image.png