JavaIO

常用文件操作

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

  • 相关方法
    new File(String pathname)
    new File(File parent,String child)
    new File(String parent,String pathname)

常用文件方法

File file=new File();

  • file.getName()
  • file.getAbsolutePath()
  • file.getlength()
  • mkdir,mkdirs,delete

IO流原理及流的分类

抽象基类 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

字节输入流:InputStream

InputStream抽象类是所有类字节输入流的超类
常用的子类

  1. 文件输入流 FileInputStream
  2. 缓冲字节输入流 BufferedInputStream
  3. 对象字节输入流 ObjectInputStream

文件输入流使用范例,从一个txt文件中读取内容,并输出到控制台。

点击查看代码
public void readFile(){ 
  String filePath = "e:\hello.txt";
  byte[] buf = new byte[8]; //一次读取8个字节
  int readLen = 0;
  FileInputStream fileInputStream = null;
  try {
  //创建 FileInputStream 对象,用于读取 文件
  fileInputStream = new FileInputStream(filePath);
  //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入
  //如果返回-1 ,表示读取完毕//如果读取正常,返回实际读取的字节数
  while ((readLen = fileInputStream.read(buf)) != -1) {
    System.out.print(new string(buf,,readLen));//显示
    }
  }catch(IOException){
    e.printStackTrace();
  }finally{
    try{
    fileInputStream.close();
    }catch(IOException){
    e.printStackTrace();
    }
    }
}

字符输入流 Reader

文件字符输入流 FileReader

  • FileReader相关方法
  1. new FileReader(File/String)
  2. read: 每次读单个字符,返回该字符,如果到文件末尾返回-1、
  3. read(char[])
  • FileWriter 使用后,必须要关闭close或者刷新fluse,否则写入不到指定文件

处理流

处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如缓冲流(BufferedReader、BufferedWriter ),转换流,对象流,打印流等。

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

posted on 2022-12-05 09:59  千千阙歌0923  阅读(13)  评论(0)    收藏  举报