Java I/O学习笔记

本文详细介绍了Java中的I/O操作,包括File类的使用,如创建、删除、重命名文件和目录遍历。接着,讨论了Java I/O流的分类,如字节流、字符流,以及输入流、输出流、节点流和处理流的概念。文中还讲解了字符流的读写操作,字节流的文件复制方法,并重点阐述了缓冲流和转换流的作用,以及它们在提高读写效率和进行编码集转换中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I/O

File类

  • 文件创建操作如下,主要涉及文件创建,删除文件,获取文件描述符等
  1. 如何创建File类的实例
    File(String filePath)
    File(String parentPath,String childPath)
    File(File parentFile,String childPath)
  2. 创建删除操作
    public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
    public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
    public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建
    public boolean delete():删除文件或者文件夹
    删除注意事项:Java中的删除不走回收站
@Test
public void test1(){
    //构造器1
    File file1 = new File("hello.txt");         // 相对路径,相对于当前module
    File file2 =  new File("D:\\hello.txt");    // 绝对路径

    System.out.println(file1);
    System.out.println(file2);

    //构造器2:
    File file3 = new File("D:\\workspace","JavaSenior");
    System.out.println(file3);

    //构造器3:
    File file4 = new File(file3,"hi.txt");
    System.out.println(file4);
    
    // 创建文件夹,mkdir不能递归创建文件夹
    boolean mkdir = file3.mkdir();
    if(mkdir){
        System.out.println("创建成功1");
    }

    // mkdirs可以递归创建文件夹
    boolean mkdir1 = file3.mkdirs();
    if(mkdir1){
        System.out.println("创建成功2");
    }

    // 创建文件、删除文件
    if(!file4.exists()){
        //文件的创建
        file4.createNewFile();
        System.out.println("创建成功");
    }else{//文件存在
        file4.delete();
        System.out.println("删除成功");
    }
}
  • 文件夹遍历操作
    public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
    public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
@Test
public void test3(){
    File file = new File("D:\\workspace_idea1\\JavaSenior");

    String[] list = file.list();
    for(String s : list){
        System.out.println(s);
    }

    System.out.println();

    File[] files = file.listFiles();
    for(File f : files){
        System.out.println(f);
    }
}
  • 文件的重命名
    public boolean renameTo(File dest):把文件重命名为指定的文件路径,也可以用于移动文件
    @Test
    public void test4(){
        
        File file1 = new File("hello.txt");
        File file2 = new File("D:\\hi.txt");
        // 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
        boolean renameTo = file1.renameTo(file2);
        System.out.println(renameTo);
    }
  • File类常用方法
方法描述
public String getAbsolutePath()获取绝对路径
public String getPath()获取路径
public String getName()获取名称
public String getParent()获取上层文件目录路径。若无,返回null
public long length()获取文件长度(即:字节数)。不能获取目录的长度
public long lastModified()获取最后一次的修改时间,毫秒值
public boolean isDirectory()判断是否是文件目录
public boolean isFile()判断是否是文件
public boolean exists()判断是否存在
public boolean canRead()判断是否可读
public boolean canWrite()判断是否可写
public boolean isHidden()判断是否隐藏
  • File类的两个常量
File.pathSeparator    //路径分隔符(于系统有关的)<windows里面是; linux里面是 :>
File.separator        //与系统有关的路径名称分隔符<windows里面是 \ linux里面是/> 

IO类与相关方法

一、流的分类:

  1. 操作数据单位:字节流、字符流
  2. 数据的流向:输入流、输出流
  3. 流的角色:节点流、处理流

二、流的体系结构

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

三、类之间的分类
在这里插入图片描述

节点流(文件流)

  1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
字符流处理
  • 读字符文件
    @Test
    public void testFileReader1()  {
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");

            //2.FileReader流的实例化
            fr = new FileReader(file);

            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            char[] cbuf = new char[1024];
            int len;
            while((len = fr.read(cbuf)) != -1){
                //方式一:
                //正确的写法
                //for(int i = 0;i < len;i++){
                //    System.out.print(cbuf[i]);
                //}

                //正确的写法
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4.资源的关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 写文件
  1. 输出操作,对应的File可以不存在的。并不会报异常
  2. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
    File对应的硬盘中的文件如果存在:
    如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
    如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
@Test
public void testFileWriter() {
    FileWriter fw = null;
    try {
        //1.提供File类的对象,指明写出到的文件
        File file = new File("hello1.txt");

        //2.提供FileWriter的对象,用于数据的写出
        fw = new FileWriter(file,false);

        //3.写出的操作
        fw.write("wo hahahaha!\n");
        fw.write("you hahahahaha!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.流资源的关闭
        if(fw != null){
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
通过字节流复制文件
  • 可以通过FileInputStream与FileOutputStream完成任意文件复制
    注:FileInputStream与FileOutputStream可以完成任意文件复制,但是FileReader与FileWriter只能完成字符流文件复制
public void copyFile(String srcPath,String destPath){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);

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

        //复制的过程
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos != null){
            //
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

处理流

缓冲流
  1. 缓冲流:
    BufferedInputStream
    BufferedOutputStream
    BufferedReader
    BufferedWriter
  2. 作用:提供流的读取、写入的速度。提高读写速度的原因:内部提供了一个缓冲区
  3. 处理流,就是“套接”在已有的流的基础上。
  • BufferedInputStream与BufferedOutputStream实现文件复制的方法
    //实现文件复制的方法
    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
          //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
          //fos.close();
          //fis.close();
        }
    }
  • 使用BufferedReader和BufferedWriter实现文本文件的复制
    @Test
    public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //一次性创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));

            //读写操作
            //方式一:使用char[]数组
            //            char[] cbuf = new char[1024];
            //            int len;
            //            while((len = br.read(cbuf)) != -1){
            //                bw.write(cbuf,0,len);
            //                bw.flush();
            //            }

            //方式二:使用String
            String data;
            while((data = br.readLine()) != null){
                bw.write(data + "\n");//data中不包含换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(bw != null){

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
转换流
  1. 转换流:属于字符流
    InputStreamReader:将一个字节的输入流转换为字符的输入流
    OutputStreamWriter:将一个字符的输出流转换为字节的输出流
  2. 作用:提供字节流与字符流之间的转换
  3. 解码:字节、字节数组 —>字符数组、字符串
    编码:字符数组、字符串 —> 字节、字节数组
  • 实现编码集的转换
@Test
public void test2() throws Exception {
    //1.造文件、造流
    File file1 = new File("dbcp.txt");
    File file2 = new File("dbcp_gbk.txt");

    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);
    
    // InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
    InputStreamReader isr = new InputStreamReader(fis,"utf-8");
    OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

    //2.读写过程
    char[] cbuf = new char[20];
    int len;
    while((len = isr.read(cbuf)) != -1){
        osw.write(cbuf,0,len);
    }

    //3.关闭资源
    isr.close();
    osw.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值