0
点赞
收藏
分享

微信扫一扫

Java IO流专题笔记

香小蕉 2022-04-23 阅读 31
java

Java IO流专题笔记

在这里插入图片描述

文件

常用文件操作

创建文件对象相关构造器方法

  • new File(String pathname);//根据路径创建一个File对象
    new File(File parent,String child);//根据父类目录文件+子路径构建
    new File(String parent,String child);//根据父类目录+子路径构造
    
  • @Test
    public void create01() throws IOException {
        String filePath = "d:\\new.txt";
        File file = new File(filePath);
    
        file.createNewFile();
    }
    

获取文件的相关信息

  • getName()

  • getAbsoultePath()

  • getParent()

  • length()

  • exsits()

  • isFile()

  • isDirectory()

    • @Test
      public void info(){
          File file = new File("F:\\毕业设计\\论文\\参考文献.txt");
          System.out.println("文件名="+file.getName());
          System.out.println("绝对路径="+file.getAbsolutePath());
          System.out.println("文件父级目录="+file.getParent());
          System.out.println("文件大小(字节)="+file.length());
          System.out.println("是否存在="+file.exists()); 
          System.out.println("是否一个文件="+file.isFile());
          System.out.println("是否一个目录="+file.isDirectory());
      }
      
  • mkdir() 创建一级目录

  • mkdirs() 创建多级目录

  • delete() 删除空目录或文件

IO流原理及流的分类

流的分类

按操作数据单位不同分类:字节流(8bit)、字符流(按字符)

按数据流的流向不同:输入流、输出流

按流的角色不同分为:节点流、处理流/包装流

抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

IO流体系图-常用类

字节流

InputStream常用子类

  • FileInputStream 文件输入流

    • //单个字节读取 效率较低 -> 使用read(byte [])优化
      @Test
      public void readFile01(){
          String filePath="F:\\毕业设计\\论文\\参考文献\\参考文献.txt";
          int readData=0;
          FileInputStream fileInputStream = null;
          try {
              fileInputStream = new FileInputStream(filePath);
              //返回-1 说明文件读取完毕
              while((readData = fileInputStream.read())!=-1){
                  //如果有文字不推荐使用 字符流 会乱码
                  System.out.print((char)readData);
              }
          } catch (IOException e) {
              e.printStackTrace();
          }finally {
              //关闭文件流,释放资源
              try {
                  fileInputStream.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
          }
      }
      
      @Test
      public void readFile02(){
          String filePath="F:\\毕业设计\\论文\\参考文献\\参考文献.txt";
          byte[] buf = new byte[8];//一次读8个字节
          int bufLen=0;
          FileInputStream fileInputStream = null;
          try {
              fileInputStream = new FileInputStream(filePath);
              //返回-1 说明文件读取完毕
              //如果读取正常,返回实际读取的字节数 最大9个
              while((bufLen = fileInputStream.read(buf))!=-1){
                  //如果有文字不推荐使用 字符流 会乱码
                  System.out.print(new String(buf,0,bufLen));
              }
          } catch (IOException e) {
              e.printStackTrace();
          }finally {
              //关闭文件流,释放资源
              try {
                  fileInputStream.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
          }
      }
      
  • BufferInputStream 缓冲字节输入流

  • ObjectInputStream 对象字节输入流

OutputStream常用子类

  • FileOutputStream 文件输出流

    • // 演示将数据写入到文件中,如果该文件不存在,则创建该文件
      @Test
      public void writeFile(){
          String filePath="F:\\毕业设计\\论文\\参考文献.txt";
          FileOutputStream fileOutputStream=null;
      
          try {
              // new FileOutputStream(filePath); 该方式是覆盖添加
              // new FileOutputStream(filePath,true); 该方式是在文件后方append添加
              fileOutputStream = new FileOutputStream(filePath);
              // 1.写入一个字节
              fileOutputStream.write('H');
              // 2.写入多个字符
              String str = "hello world";
              fileOutputStream.write(str.getBytes());
              // 3.指定字符长度写入
              fileOutputStream.write(str.getBytes(),0,2);
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
          }
      }
      

文件拷贝

代码演示

@Test
public void fileCopy(){
    String oldFilePath = "F:\\毕业设计\\论文\\图\\借阅信息主动推送.png";
    String newFilePath = "F:\\毕业设计\\论文\\借阅信息主动推送.png";
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    byte[] bytes = new byte[8];
    int len=0;
    try {
        fileInputStream = new FileInputStream(oldFilePath);
        fileOutputStream = new FileOutputStream(newFilePath);
        while((len = fileInputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

字符流

FileReader和FileWriter介绍

FileReader相关方法

  • new FileReader(File/String);
    
    read();//每次读取单个字符,返回字符,如果文件末尾返回-1
    
    reader(char[]); //批量读取多个字符数组,返回读到的字符数,如果文件末尾返回-1
    //相关API
    new String(char[]); //将char[]转换成String
    new String(char[],off,len);//将char[]的指定内容换砖成String'
    
  • //读取文件 
    @Test
    public void fileReader(){
        String filePath="F:\\毕业设计\\论文\\参考文献\\参考文献.txt";
        FileReader fileReader = null;
        int readerData=0;
        try {
            fileReader = new FileReader(filePath);
            while((readerData = fileReader.read()) != -1){
                System.out.print((char)readerData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

FileWriter常用方法

  • new FileWriter(File/String); //覆盖模式,相当于流的指针首段
    
    new FileWriter(File/String,true); //追加模式,相当于流的指针再尾端
    
    write(int); //写入单个地府
    
    write(char[]); //写入指定数组
    
    write(char[],off,len); //写入指定数组的指定部分
    
    write(String); //写入整个字符串
    
    write(String,off,len); //写入字符串的指定部分
    
    //相关API
    String.toCharArray(); //将String转换成char[]
    //注意
    //FileWriter使用后,必须要关闭(close) 或 刷新(flush),否则写入不到指定的文件
        
    

节点流和处理流

节点流和处理流的区别和联系

区别

  1. 节点流是底层流/低级流,直接跟数据源相接
  2. 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入和输出
  3. 处理流(包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相联

处理流的功能主要体现方面

  1. 性能的提高:主要以增加缓冲的方式来提高输入输出效率
  2. 操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便

处理流BufferedReader 和 BufferedWriter

处理流 BufferedInputStream 和 BufferedOutputSteam

图片拷贝

package main.java.com.chapter19.FileCopy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @Author BaoYuan
 * @CreateDate 2022/4/21 19:13
 * @Version 1.0
 */
public class BufferedStreamCopy {
    public static void main(String[] args) throws Exception {
        String oldFilePath="F:\\毕业设计\\论文\\借阅信息主动推送.png";
        String newFilePath="F:\\毕业设计\\论文\\借阅信息主动推送2.png";
        byte[] ch =  new byte[8];
        int res = 0;
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(oldFilePath));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFilePath));
        while((bufferedInputStream.read(ch)) != -1){
                bufferedOutputStream.write(ch);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }
}

对象流 ObjectInputStream 和 ObjectOutputStream(序列化、反序列化)

序列化实现

package main.java.com.chapter19.outputStream_;

import main.java.com.test.E;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @Author BaoYuan
 * @CreateDate 2022/4/21 21:13
 * @Version 1.0
 */
public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception {
        //序列化后保存文件格式并非自己设计
        String filePath = "F:\\毕业设计\\论文\\data.text";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

        oos.write(100);
        oos.writeUTF("啊啊啊");
        oos.writeBoolean(true);
        oos.writeObject(new Dog("旺财",2));
        oos.close();
    }
}

class Dog implements Serializable{
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

反序列化实现

package main.java.com.chapter19.InputStream;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * @Author BaoYuan
 * @CreateDate 2022/4/21 21:37
 * @Version 1.0
 */
public class ObjectInputStream_ {
    public static void main(String[] args) throws Exception {
        String filePath = "F:\\毕业设计\\论文\\data.text";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

        //读取的顺序 必须与写入时一样 否则抛出异常
        System.out.println(ois.readInt());
        System.out.println(ois.readUTF());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readObject());

        ois.close();

    }
}
注意事项

标准输入输出流

转换流 InputStreamReader 和 OutputStreamWriter

打印流 PrintStream 和 PrintWriter

Properties类

举报

相关推荐

0 条评论