• JAVA基础(二十七)——文件相关操作


    一、目录

    • 文件流
    • 文件相关操作
    • IO流原理及流的分类
    • IO流常用的类

    二、文件流

    文件在程序中是以流的形式来操作的。

    java程序—>文件(输出流)
    文件—>java程序(输入流)

    流:数据在数据源(文件)和程序(内存)之间经历的路径。

    输入流:数据从数据源(文件)到程序(内存)的路径。
    输出流:数据从程序(内存)到数据源(文件)的路径。

    三、文件相关操作

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

      相关方法
      new File(String pathname) //根据路径构建一个File对象。
      new File(File parent, String child) //根据父目录文件+子路径构建。
      new File(String parent, String child) //根据父目录 + 子路径构建
      createNewFile 创建新文件

    package com.javafile;
    
    import java.io.File;
    import java.io.IOException;
    
    public class CreateFile {
        public static void main(String[] args) {
            File file = new File("E:\\","dd.txt");
            try {
                file.createNewFile();
                System.out.println("File Create Successfully");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    //File Create Successfully
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 获取文件相关信息
      • getName 获取文件名
      • getAbsolutePath 获取文件绝对路径
      • getParent 获取文件的父级目录
      • length 获取文件大小
      • exists 查看文件是否存在
      • isFile 查看是否是一个文件
      • isDirectory 查看是否为一个目录
    package com.javafile;
    
    import java.io.File;
    
    public class GetFileInfo {
        public static void main(String[] args) {
            File file = new File("E:\\code\\java\\code\\dd.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());
        }
    
    }
    
    dd.txt
    E:\code\java\code\dd.txt
    E:\code\java\code
    0
    true
    true
    false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 目录操作和文件删除

      mkdir创建一级目录
      mkdirs创建多级目录
      delete删除空目录或文件

    package com.javafile;
    
    import java.io.File;
    
    public class DirOper {
        public static void main(String[] args) {
            File file = new File("E:\\code\\java\\code\\dd.txt");
            if(file.exists()){
                if(file.delete()){
                    System.out.println("The file delete successfully");
                }
            }else {
                System.out.println("The file is not exist");
            }
            File file1 = new File("E:\\code\\java\\code\\a\\b\\c");
            if(file1.exists()){
                System.out.println("The directory exists");
            }else {
                if(file1.mkdirs()){
                    System.out.println("The Directory creates successfully");
                }else {
                    System.out.println("The Directory creates failed");
                }
            }
        }
    }
    
    The file is not exist
    The Directory creates successfully
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    四、IO流原理及流的分类

    • Java IO流原理
      1. I/O流也就是输入输出流,I/O技术用于处理数据传输,如读写文件,网络通讯等。
      2. Java程序中,对于数据的输入输出操作以流(stream)的方式进行。
      3. java.io包下提供了各种流的类和接口,用以获取不同种类的数据,并通过方法输入或输出数据。
    • 流的分类
      • 按操作数据单位不同分为:字节流(8 bit)(用于二进制文件)、字符流(按字符)(用于文本文件)。
      • 按数据流的流向不同分为:输入流、输出流。
      • 按流的角色不同分为:节点流、处理流/包装流。
    抽象基类字节流字符流
    输入流InputStreamReader
    输出流OutputStreamWriter

    Java的IO流共涉及40多个类,实际上非常规则,都是从上面4个抽象基类派生的。
    由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

    五、IO流常用的类

    • InputStream:字节输入流

      InputStream抽象类是所有类字节输入流的父类。

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

      1. FileOutputSteam:文件输出流

    FileInputStream示例代码:

    单个字节的方式读取文件内容(使用read()),效率较低:

    package com.javainputstream;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class File_Input_Stream {
        public static void main(String[] args) {
            String filepath = "E:\\code\\java\\code\\dd.txt";
            int readdata = 0;
            FileInputStream fileInputStream = null;
            try {
                //创建FileInputStream对象,用于读取filepath的文件
                fileInputStream = new FileInputStream(filepath);
                while((readdata = fileInputStream.read()) != -1){
                    System.out.print((char)readdata);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    hello,this is me.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    因为单个字节读取效率低下,用read(byte[] b)的方式改进:

    package com.javainputstream;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class File_Input_Stream {
        public static void main(String[] args) {
            String filepath = "E:\\code\\java\\code\\dd.txt";
            int readlenth = 0;
            FileInputStream fileInputStream = null;
            byte[] buffer = new byte[8];  //一次读取8个字节
            try {
                //创建FileInputStream对象,用于读取filepath的文件
                fileInputStream = new FileInputStream(filepath);
    
                //read(byte[] b) 如果读取正常,返回实际读取的字节数
                while((readlenth = fileInputStream.read(buffer)) != -1){
                    System.out.print(new String(buffer, 0, readlenth));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    hello,this is me.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    FileOnputStream示例代码:

    1.按字节写入 fileOutputStream.write(‘a’);
    2.如果想写入字符串,用getBytes()方法,它可以将一个字符串转成一个字节数组。
    3.write方法也接收offset,write(data.getBytes(), 0, data.length());。
    4.如果不要覆盖,想追加写入,那么new FileOutputStream(filepath, true),加上第二个参数true,来创建FileOutputStream对象,它就是追加的。

    package com.javainputstream;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class File_Output_Stram {
        public static void main(String[] args) {
            String filepath = "E:\\code\\java\\code\\dd.txt";
            FileOutputStream fileOutputStream = null;
    
            try {
                fileOutputStream = new FileOutputStream(filepath);
    
                //按字节写入
                //fileOutputStream.write('a');
    
                //写入字符串,用getBytes()方法,它可以将一个字符串转成一个字节数组。
                String data= "Hello,do you miss me?";
                fileOutputStream.write(data.getBytes());
                //fileOutputStream.write(data.getBytes(), 0, data.length());
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • FileReader和FileWriter介绍

      FileReader和FileWriter是字符流,即按照字符来操作io。

      FileReader相关方法:

      1. new FileReader(File/String)
      2. read:每次读取单个字符,返回该字符,如果到文件末尾返回-1。
      3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1.
        相关api:
      4. new String(char[]):将char[]转换成String。
      5. new String(char[], offset, length):将char[]指定的部分转换成String。

      FileWriter相关方法:

      1. new FileWriter(File/String):覆盖模式,相当于流的指针在首端。
      2. new FileWriter(File/String, true):追加模式,相当于流的指针在尾端。
      3. write(int):写入单个字符。
      4. write(char[]):写入指定字符数组。
      5. write(char[], offset, length):写入指定数组的指定部分。
      6. write(string):写入整个字符串。
      7. write(string, offset, length):写入字符串的指定部分。
        相关api:
        String类的toCharArray:将String转换成char[]。
        注意
        FileWriter使用后,必须要关闭close或者刷新flush,否则写入不到指定的文件。

    FileReader示例代码:

    package com.javainputstream;
    
    import java.io.FileReader;
    import java.io.IOException;
    
    public class File_reader {
        public static void main(String[] args) {
            String filepath = "E:\\code\\java\\code\\dd.txt";
            FileReader fileReader = null;
            int readdata = 0;
            try {
                fileReader = new FileReader(filepath);
                while ((readdata = fileReader.read()) != -1){
                    System.out.print((char) readdata);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    
    Hello,do you miss me?
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    FileWriter示例:

    package com.javainputstream;
    
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class File_Writer {
        public static void main(String[] args) {
            String filepath = "E:\\code\\java\\code\\dd.txt";
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(filepath, true);
                String data = "yes, i miss you every much!";
                fileWriter.write(data);
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
  • 相关阅读:
    算法面试题:字符串反转
    遇到问题[已解决]TypeError: ‘odict_keys‘ object is not subscriptable
    OpenCV学习(五)——图像基本操作(访问图像像素值、图像属性、感兴趣区域ROI和图像边框)
    【VUE 获取PDF文档流直接打印】
    从Spring迁移到Spring Boot
    .NET 8 IEndpointRouteBuilder详解
    前端表单滑块验证码开发
    数据结构(栈和队列)
    Chainlit vs Streamlit和Gradio:为什么Chainlit是开发聊天机器人不错的选择
    罗丹明标记的葡聚糖 70k,RB-Dextran,MW:70K
  • 原文地址:https://blog.csdn.net/qq_37466661/article/details/126495235