Java高级编程知识—10、IO流

10.1 File类

  1. java.io.File类的一个对象,代表一个文件或文件目录

  2. 构造器创建File实例:

    1. File(String filePath)
    2. File(String parent, File child)
    3. File(File parent, String child)
  3. 路径分隔符:

    • windows和DOS系统默认使用“\”表示

    • UNIX和URL使用“/”表示

    • 为了解决此隐患,File类提供了一个常量public static final String separator:根据操作系统动态的提供分隔符

    • 注:

      • Idea中:Junit单元测试方法中相对路径为当前module下,main()方法中相对路径为当前project下
      • Eclipse中:两种方法的相对路径都为当前project下
  4. File类中涉及到关于文件(目录)的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如需读取或写入文件内容,必须使用IO流来完成

  5. 后续File类的秀爱给你常会作为参数传递到流的构造器中,指明读取或写入的“终点”

常用方法:

  1. String getAbsolutePath():获取绝对路径
  2. String getPath():获取路径
  3. String getName():获取名称
  4. String getParent():获取上层文件目录路径,若无返回null
  5. long length():获取文件长度(字节数),不能获取目录长度
  6. long lastModified():获取最后一次修改时间,毫秒值
  7. boolean renameTo(File dest):将此文件重命名为指定的文件路径
    • 要求:此文件在硬盘中存在,dest文件在硬盘中不存在
  8. boolean exists():判断是否存在
  9. boolean isDirectory():判断是否是文件目录
  10. boolean isFile():判断是否是文件
  11. boolean canRead():判断是否可读
  12. boolean canWrtite():判断是否可写
  13. boolean isHidden():判断是否是隐藏的

如下方法适用于文件目录:

  1. String[ ] list():获取指定目录下的所有文件或文件目录的名称数组
  2. File[ ] listFiles():获取指定目录下的所有文件或文件目录的File数组

创建文件(目录)

  1. boolean createNewFile():创建文件,若文件已存在则不创建,返回false

    File file = new File("create.txt");
            if(!file.exists()){
                file.createNewFile();
                System.out.println("创建成功!");
            }else{
                file.delete();
                System.out.println("删除成功!");
            }
    
  2. boolean mkdir():创建文件目录,若已存在或上层目录不存在则不创建,返回false

  3. boolean mkdirs():创建文件目录,若上层目录不存在,则一并创建

删除文件(目录)

boolean delete():删除文件(目录),若文件目录中有内容则不删除,返回false

10.2 IO流原理、分类

IO流概述
  • IO:Input / Output的缩写,处理设备之间的数据传输,如读写文件、网络通讯等

  • 流:数据的输入输出的标准化方式

流的分类

  • 按操作数据单位:
    • 字节流(8bit)图片、视频
    • 字符流(16bit)文本
  • 按数据流流向:输入流、输出流
  • 按流的角色:节点流、处理流
(抽象基类)字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

由这四个类派生出来的子类名都是以其父类名作为后缀的

IO流体系

抽象基类节点流(文件流)缓冲流(处理流的一种)
InputStreamFileInputStream:int read(byte[] buffer)BufferedInputStream:int read(byte[] buffer)
OutputStreamFileOutputStream:write(byte[] buffer,0,len)BufferedOutputStream:write(byte[] buffer,0,len)、flush()
ReaderFileReader:int read(char[] cbuf)BufferedReader:int read(char[] cbuf)、 String readLine()
WriterFileWriter:write(char[] cbuf,0,len)BufferedWriter:write(char[] cbuf,0,len)、flush()

输入输出的标准化过程

  1. 输入过程
    1. 创建File类的对象,指明读取的数据的来源(要求此文件一定存在
    2. 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
    3. 具体的读入过程:创建相应的byte[]或char[]
    4. 关闭流资源
  2. 输出过程
    1. 创建File类的对象,指明读取的数据的来源(此文件可以不存在
    2. 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
    3. 具体的写出过程:write(char[] / byte[] buffer,0,len)
    4. 关闭流资源

说明:程序中出现的编译时异常要使用try-catch0finally处理

FileReader

read():返回读入的一个字符,如果达到末尾则返回-1

//1、实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");
FileReader fr = null;
//2、将文件作为形参,提供具体的流
try {
    fr = new FileReader(file);
    //3、数据的读入
    int data;
    while ((data = fr.read()) != -1) {
        System.out.println((char) data);
    }
}catch (IOException e){
    e.printStackTrace();
}finally {
    //4、流的关闭操作
    try {
       if(fr!=null)
        fr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

说明:

  1. read():返回读入的一个字符,如果达到末尾则返回-1
  2. 异常处理:为了保证流资源一定可以执行关闭操作,需要用try-catch-finally处理
  3. 读入的文件一定要存在,否则就会报FileNotFoundException

read(char[ ] cbuf):返回每次读入cbuf数组的字符个数,如果到达文件末尾则返回-1

File file = new File("hello.txt");
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            char[] cbuf = new char[5];
            int len;
            //read(char[] cbuf):返回每次读入cbuf数组的字符个数,如果到达文件末尾则返回-1
//			方式一
//            while((len=fr.read(cbuf))!=-1){
//                for (int i = 0; i <len ; i++) {
//                    System.out.print(cbuf[i]);
//                }
//            }
//			方式二
            while((len=fr.read(cbuf))!=-1){
                String str = new String(cbuf, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fr!=null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
FileWriter
File file = new File("hello1.txt");
FileWriter fw = null;
try {
    fw = new FileWriter(file);
    fw.write("I have a dream!\n".toCharArray());
    fw.write("you need to have a dream");
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if(fw!=null)
            fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

说明:

  1. 输出操作:对应的File可以不存在
    • 若File不存在,则在输出的过程中自动创建
    • 若File存在:
      • 如果流使用的构造器是:FileWriter(file,false)或FileWriter(file),则对原有文件内容进行覆盖
      • 如果流使用的构造器是:FileWriter(file,true),则在原有文件内容末尾进行添加

练习:

File字符流复制文本文件

File srcFile = new File("hello.txt");
File tgtFile = new File("hello2.txt");
FileReader fr = null;
FileWriter fw = null;

try {
    fr = new FileReader(srcFile);
    fw = new FileWriter(tgtFile);

    char[] cbuf = new char[5];
    int len;
    while((len = fr.read(cbuf))!=-1){
        fw.write(cbuf,0,len);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if(fw!=null)
            fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if(fr!=null)
            fr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

FileInputStream、FileOutputStream与FileReader、FileWriter的用法类似

结论:

  1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流FileReader、FileWriter处理
  2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt),使用字节流FileInputStream、FileOutputStream处理
  3. 如果只是复制文件,可以用字节流复制文本文件(只传输不打印),但不可用字符流复制非文本文件

10.3 处理流

*缓冲流
  1. 缓冲流:

    BufferedInputStream

    BufferedOutputStream

    BufferedReader

    BufferedWriter

  2. 作用:提高流的读取、写入的速度

    原因:内部提供了一个缓冲区

  3. 处理流,就是“套接”在已有的流上

练习:

缓冲流BufferedInputStream、BufferedOutputStream复制非文本文件

public void copyFile(String srcfile, String destfile) {
    File srcFile = new File(srcfile);
    File destFile = new File(destfile);
    FileInputStream fis = null;
    FileOutputStream fos = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);

        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        byte[] buffer = new byte[1024];

        int len;
        while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null)
                bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (bos != null)
                bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

要求:先关闭外层处理流,再关闭内层节点流

说明:关闭外层流时,内层流也会自动关闭,因此可以省略内层流的关闭操作

练习:

缓冲流BufferedReader、BufferedWriter复制文本文件

public void copyFile(String srcfile, String desffile){
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            br = new BufferedReader(new FileReader(new File(srcfile)));
            bw = new BufferedWriter(new FileWriter(new File(desffile)));
            char[] cbuf = new char[1024];

//            方法一:
//            int len;
//            while((len=br.read(cbuf))!=-1){
//                bw.write(cbuf,0,len);
//            }

//            方法二:
            String data;
            while((data=br.readLine())!=null){
//                bw.write(data+"\n");
                bw.write(data);
                bw.newLine();
            }
//            readLine()不包含换行符,需要手动添加

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
*转换流
  1. 转换流:属于字符流

    InputStreamReader:将一个字节的输入流转换为字符的输入流(解码)

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

  2. 作用:提供字节流与字符流之间的转换(编码)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-byaArK4f-1642867698063)(C:\Users\HP\AppData\Roaming\Typora\typora-user-images\image-20220121110642231.png)]

public void test() throws IOException {
    FileInputStream fis = new FileInputStream("text.txt");
    InputStreamReader isr = new InputStreamReader(fis,"utf-8");
	//参数2指明了字符集,取决于要读写的文件使用的字符集
    char[] cbuf = new char[20];
    int len;
    while((len=isr.read(cbuf))!=-1){
        System.out.print(new String(cbuf,0,len));
    }
    isr.close();
}
标准输入输出流
  1. System.in:标准输入流:默认从键盘输入

    System.out:标准输出流:默认从控制台输出

  2. 通过System类的setIn()、setOut()方法可对默认设备进行更改

    • public static void setIn(InputStream in)
    • public static void setOut(PrintStream out)

练习:从键盘输入字符串,不断将读取到的整行字符串转换成大写输出,直至输入e或exit时退出程序

public static void main(String[] args)  {
    BufferedReader br = null;
    try {
        InputStream in = System.in;  //字节流
        InputStreamReader isr = new InputStreamReader(in);  //用转换流将字节流转换为字符流
        br = new BufferedReader(isr);
        while (true) {
            System.out.println("请输入字符串:");
            String str = br.readLine();
            if(str == null || "e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str))
                break;
            System.out.println(str.toUpperCase());
        }
        System.out.println("goodbye!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(br!=null)
                br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
打印流

PrintStream和PrintWriter

  • 提供了一系列重载的print()和println()方法,输出多种数据类型
  • 输出不会抛IOException异常
  • 有自动flush功能
  • PrintStream打印的所有字符都使用平台默认字符编码转换为字节
    • 在需要写入字符而不是字节的情况下,应该使用PrintWriter类
  • System.out返回的是PrintSream类

练习:设置文件输出打印流

public void test2() throws IOException {
        FileOutputStream fos = new FileOutputStream("printStream.txt");
//        创建打印输出流,设置为自动刷新flush模式(写入换行符或字节'\n'时会自动刷新输出缓冲区
        PrintStream ps = new PrintStream(fos,true);
        System.setOut(ps);
        for(int i=0;i<256;i++){
            System.out.print((char)i);
            if(i%50==0) System.out.println();
        }
        ps.close();
    }
数据流
  1. DataInputStream和DataOutputStream
  2. 作用:读取、写出基本数据类型或字符串变量

注:读取各类型数据的顺序要与写入文件时的顺序一致

练习:

public void test3() throws IOException {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
    dos.writeUTF("刘德华");
    dos.writeInt(23);
    dos.writeBoolean(true);
    dos.close();
}

public void test4() throws IOException {
    DataInputStream dos = new DataInputStream(new FileInputStream("data.txt"));
    String name = dos.readUTF();
    int age = dos.readInt();
    boolean male = dos.readBoolean();
    System.out.println("name = " + name);
    System.out.println("age = " + age);
    System.out.println("male = " + male);
    dos.close();
}
*对象流
  1. ObjectInputStream和ObjectOutputStream
  2. 作用:用于存储和读取基本数据类型数据或对象的处理流,可以把Java中的对象写入到数据源中(序列化),也能把对象从数据源中还原回来(反序列化)

对象需要满足如下的要求,方可序列化

  1. 所在类要实现Serializable接口
  2. 所在类要声明一个全局常量:public static final long serialVersionUID = xxxxxxxxxL; (为了版本控制)
  3. 除了所在类要实现Serializable接口之外,还必须保证类内部所有属性也是可序列化的(默认情况下,基本数据类型可序列化)

补充:不能序列化statictransient修饰的成员

序列化过程:将内存中的Java对象保存到磁盘中或通过网络传输出去,使用ObjectOutputStream实现

public void test(){
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush(); //刷新操作
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(oos!=null)
                oos.close();
        }catch (IOException e) {
                e.printStackTrace();
            }
    }

}

反序列化过程:将磁盘文件、网络流中的对象还原为内存中的一个java对象,需要使用ObjectInputStream实现

public void test1(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("obj.dat"));
        Object obj = ois.readObject();
        String str = (String)obj;
        System.out.println(str);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if(ois!=null)
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}
随机存取文件流

RandomAccessFile

  1. RandomAccessFile直接继承于Object类
  2. 实现了DataInput、DataOutput接口,意味着这个类既可以读也可以写
  3. 作为输出流时,如果写出的文件不存在则自动创建,如果存在则会对原有内容进行覆盖(默认从头开始覆盖)
  4. 可以通过reek调整指针,实现“插入”数据

构造器

  • public RandomAccessFile(File file, String mode)
    
  • public RandomAccessFile(String name, String mode)
    

mode参数指定RandomAccessFile的访问模式:

r:以只读方式打开

rw:打开以便读取和写入

rwd:打开以便读取和写入;同步文件内容的更新

rws:打开以便读取和写入;同步文件内容和元数据的更新

public void test2() throws IOException{
    RandomAccessFile raf = new RandomAccessFile("hello.txt", "rw");
    raf.seek(3);//将指针调到角标为3的位置
    raf.write("xyz".getBytes());
    raf.close();
}

通过reek调整指针,实现“插入”数据

    public void test3() throws IOException {
        int pos = 3;
        File file = new File("hello.txt");
        RandomAccessFile raf = new RandomAccessFile(file,"rw");
        raf.seek(pos);
        byte[] buffer = new byte[20];
        int len;
//        保存指针pos后的所有数据到StringBuilder中
        StringBuilder str = new StringBuilder((int) file.length());
        while((len=raf.read(buffer))!=-1){
           str.append(new String(buffer,0,len));
        }
//        调回指针,写入xyz
        raf.seek(pos);
        raf.write("xyz".getBytes());
        raf.write(str.toString().getBytes());
        raf.close();
    }

我的学习笔记有更多精彩内容哦
Java编程知识专栏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值