Java基础复习 —— IO流1

IO流

文件

  1. 文件是存储数据的地方,包括文字,图片,音乐和视频等等
  2. 文件在程序中以 的形式来操作

​ 文件流

image

  • :数据在数据源(文件)和程序(内存)之间经历的路径
  • 输入流:数据从数据源(文件)到程序(内存)的路径
  • 输入流:数据从程序(内存)到数据源(文件)的路径

常用的文件操作

image

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

image

new File(String pathname) // 根据路径构建一个File对象
new File(File parent, String child) // 根据父目录文件 + 子路径构建
new File(String parent, String child) // 根据父目录 + 子路径
    
public boolean createNewFile() // 创建新文件
  • 获取文件的相关信息

    // 列举出较常用的
    
    String	getName()
    Returns the name of the file or directory denoted by this abstract pathname.
    
    String	getPath()
    Converts this abstract pathname into a pathname string.
    String	getAbsolutePath()
    Returns the absolute pathname string of this abstract pathname.    
        
    String	getParent()
    Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
        
    boolean	delete()
    Deletes the file or directory denoted by this abstract pathname.
        
    boolean	exists()
    Tests whether the file or directory denoted by this abstract pathname exists.
        
    boolean	isDirectory()
    Tests whether the file denoted by this abstract pathname is a directory.    
    boolean	isFile()
    Tests whether the file denoted by this abstract pathname is a normal file.
    
    long	length()
    Returns the length of the file denoted by this abstract pathname.
        
    boolean	mkdir()
    Creates the directory named by this abstract pathname.
    boolean	mkdirs()
    Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.    目录的操作和文件删除
    
  • 目录的操作和文件删除

    // 判断文件是否存在,存在就删除
    if (file.exists()) {
        if (file.delete()) {
            System.out.println("文件:" + file.getName() + "删除成功");
        } else {
            System.out.println("文件:" + file.getName() + "删除失败");
        }
    } else {
         System.out.println("该文件不存在");
    }
    
    // 目录是否存在,存在就提示,否则创建
     String directoryPath = "F:\\VSCode\\JAVA\\file\\test\\a\\b\\c\\d\\e\\f\\g";
     File file = new File(directoryPath);
    
    if(file.exists()) {
        System.out.println(directoryPath + " 已存在");
    } else {
        if (file.mkdirs()){
            System.out.println(directoryPath + " 创建成功!");
         }else {
            System.out.println(directoryPath + " 创建失败!");
         }
    }
    

IO流原理和流的分类

java IO流原理

  1. IO是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写文件,网络通讯等。

  2. Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行

  3. java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

  4. 输入input: 读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中

  5. 输出output: 将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类

  • 操作数据单位不同分为:字节流(8bit)二进制文件,字符流(按字符)文本文件

  • 按数据流的流向不同分为:输入流输出流

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

    抽象基类 字节流 字符流
    输入流 InputStream Reader
    输出流 OutputStream Writer
    • Java的1O流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。

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

IO 流体系图

img

[图片来源](JAVA IO流结构图概览_布鲁斯1990的博客-CSDN博客)

FileInputStream 和 FileOutputStream

  1. FileInputStream

image

public void readFile01() {
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\the Zen of Python.txt";
//        String filePath = "F:\\VSCode\\JAVA\\file\\test\\hello.txt";
        int readData = 0;

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            // Reads a byte of data from this input stream. This method blocks if no input is yet available.
            //Returns: the next byte of data, or -1 if the end of the file is reached.k
//            while ((readData = fileInputStream.read()) != -1) {
//                System.out.print((char)readData);
//            }
            // ASCII 码中,一个英文字母(不分大小写)为一个字节,一个中文汉字为两个字节。
            //UTF-8 编码中,一个英文字为一个字节,一个中文为三个字节。
            //Unicode 编码中,一个英文为一个字节,一个中文为两个字节。
            readData = fileInputStream.read();
            System.out.println(fileInputStream.available());
            System.out.print((char) readData);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

// 使用 read(byte[] b) 读取文件,提高效率
 public void readFile02() {
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\the Zen of Python.txt";
//        String filePath = "F:\\VSCode\\JAVA\\file\\test\\hello.txt";
        int readData = 0;
        // 字节数组
        byte[] bytes = new byte[8]; // 一次读取8个字节
        int readlen = 0;

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            System.out.println(fileInputStream.available());

            // Returns: the total number of bytes read into the buffer, or -1 if
            // there is no more data because the end of the file has been reached.
            while ((readlen = fileInputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, readlen));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  1. FileOutputStream

image-20230719223505542

public void writeFile() {
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\hello01.txt";
        FileOutputStream fileOutputStream = null;

        try {
            // 得到一个FileOutputStream 对象
            fileOutputStream = new FileOutputStream(filePath, true);
            // 写入一个字节
//            fileOutputStream.write('a');
            // 写入字符串
            String str = "Hello, Java";
            // return : The resultant byte array
//            fileOutputStream.write(str.getBytes());
            fileOutputStream.write(str.getBytes(),  0, 5);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

实例,利用 FileInputStream 和 FileOutputStream 完成图片,音乐和视频的Copy

public void move01() {
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\ai.jpg";
//        String filePath = "F:\\VSCode\\JAVA\\file\\test\\No One But You.mp3";
        String dest = "F:\\VSCode\\JAVA\\file\\test05";
        File DestDirectory = new File(dest);

        if (DestDirectory.exists()) {
            System.out.println(dest + "已存在");
        } else {
            if (DestDirectory.mkdirs()) {
                System.out.println(dest + "创建成功");
            } else {
                System.out.println(dest + "创建失败");
            }
        }


        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        byte[] bytes = new byte[1024];
        int readLen = 0;

        try {
            fileInputStream = new FileInputStream(filePath);
//            fileOutputStream = new FileOutputStream(dest + "\\copy.jpg", true);
            fileOutputStream = new FileOutputStream(dest + "\\copy.jpg");
//            fileOutputStream = new FileOutputStream(dest + "\\copy.mp3", true);
            while ((readLen = fileInputStream.read(bytes)) != -1) {
//                System.out.println(Arrays.toString(bytes));
//                System.out.println(new String(bytes));
                fileOutputStream.write(bytes, 0, readLen);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                // 先打开的后关
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	

FileReader 和 FileWriter

  1. FileReader
    image
public void m1(){
        // 要读取的文件
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\FileReader01.java";
        FileReader fileReader = null;
        int readData = 0;


        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用 read, 单个字符读取
            while ((readData = fileReader.read()) != -1) {
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void m2(){
        //  字符数组读取文件
        // 要读取的文件
//        String filePath = "F:\\VSCode\\JAVA\\file\\test\\FileReader01.java";
//        String filePath = "F:\\VSCode\\JAVA\\file\\test\\vim学习.docx";
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\the Zen of Python.txt";
        FileReader fileReader = null;
        char[] chars = new char[8];
        int lens;


        try {
            fileReader = new FileReader(filePath);
            while ((lens = fileReader.read(chars)) != -1) {
                System.out.print(new String(chars, 0, lens));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  1. FileWriter
    image
@Test
    public void m1() {
        String filePath = "F:\\VSCode\\JAVA\\file\\test\\FileWriter.test";
//        File file = new File(filePath);

        FileWriter fileWriter = null;
        char[] chars = {'a', 'b', 'c'};
        try {
            fileWriter = new FileWriter(filePath);
//            fileWriter.write("fileWriter.write(\"\");\n"); // //默认是覆盖写入
            fileWriter.write('A'); // 写入单个字符 
            fileWriter.write(chars); // 写入指定数组
            fileWriter.write("墨染启明的ID".toCharArray(), 0, 4); // 写入指定数组的指定部分
            fileWriter.write("墨染启明的ID"); // 写入整个字符串
            fileWriter.write("墨染启明的ID", 2, 4); // 写入字符串的指定部分
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
//                fileWriter.close();
                fileWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
posted @ 2023-07-19 23:05  墨染启明  阅读(7)  评论(0编辑  收藏  举报