Java里面的IO流基础知识

IO流体系

字节流

InputStream(抽象类)

FileInputStream(基本流)
  • 第一个单词表示他的作用

  • 第二个单词表达他的继承结构

在Java中,FileInputStream 是 Java 输入/输出 (IO) 库中的一个类,用于从文件中读取字节数据。它是 InputStream 的一个子类,专门用于从文件中读取数据。

用途:

FileInputStream 主要用于从文件中读取字节数据。当你需要从文件中读取数据以进行进一步处理时,可以使用 FileInputStream

如何使用:

使用 FileInputStream 的基本步骤如下:

  1. 创建 FileInputStream 对象:通过提供文件路径或 File 对象来创建 FileInputStream 对象。
FileInputStream fis = new FileInputStream("example.txt");

或者

File file = new File("example.txt");
FileInputStream fis = new FileInputStream(file);
  1. 读取数据:使用 read() 方法从文件中读取数据。这个方法有多个重载版本,可以接受不同的参数,如 byte[] 数组用于批量读取数据。
int read;
while ((read = fis.read()) != -1) {
    // 处理读取到的字节,例如打印为字符(注意字符编码)
    System.out.print((char) read);
}

或者,使用字节数组批量读取:

byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
    // 处理读取到的字节数组,例如转换为字符串(注意字符编码)
    String data = new String(buffer, 0, bytesRead);
    System.out.print(data);
}
  1. 关闭流:使用 close() 方法关闭流。这是一个重要的步骤,可以确保释放与流关联的所有系统资源。
fis.close();
注意事项:
  1. 异常处理FileInputStream 的构造函数和 read() 方法都可能抛出 IOException。因此,你应该使用 try-catch 块来处理这些异常,或者使用 try-with-resources 语句来自动关闭流。
  2. 关闭流:确保在完成文件读取后关闭流。这可以通过在 finally 块中关闭流或使用 try-with-resources 语句来实现。
  3. 字符编码:当从文件中读取字节并将其转换为字符串时,需要注意字符编码。默认情况下,Java 使用平台的默认字符集。如果需要特定的字符编码(如 UTF-8),请使用相应的 String 构造函数或解码器。
  4. 文件路径和权限:确保指定的文件路径是有效的,并且程序有足够的权限来读取该文件。否则,可能会抛出 FileNotFoundExceptionSecurityException
  5. 缓冲区:对于大量数据的读取,建议使用缓冲区(如 BufferedInputStream)来提高性能。这可以减少对底层操作系统的调用次数,从而提高读取效率。
BufferedInputStream(高级流)
  • 第一个单词表示他的作用

  • 第二个单词表达他的继承结构

OutputStream(抽象类)

FileOutputStream(基本流)
  • 第一个单词表示他的作用

  • 第二个单词表达他的继承结构

在Java中,FileOutputStream是Java IO库中的一个类,用于将数据写入文件。它是OutputStream的一个子类,专门用于文件写入操作。

用途:

FileOutputStream主要用于将数据(如字节数组、字符串等)写入到文件中。当你需要将数据保存到磁盘上以便后续读取或处理时,可以使用FileOutputStream

如何使用:

使用FileOutputStream的基本步骤如下:

  1. 创建FileOutputStream对象:指定要写入的文件名(可以是绝对路径或相对路径)。
FileOutputStream fos = new FileOutputStream("output.txt");

或者,如果你想在文件的末尾追加内容而不是覆盖现有内容,可以使用true作为第二个参数:

FileOutputStream fos = new FileOutputStream("output.txt", true);
  1. 写入数据:使用write()方法将数据写入文件。这个方法有多个重载版本,可以接受不同的参数类型,如int(单个字节)、byte[](字节数组)等。
String data = "Hello, World!";
fos.write(data.getBytes());

或者,如果你有一个字节数组:

byte[] buffer = ...; // 填充你的数据
fos.write(buffer);
  1. 关闭流:完成写入后,使用close()方法关闭流。这是一个重要的步骤,因为它会确保所有数据都被刷新到磁盘,并释放与该流关联的任何系统资源。
fos.close();
注意事项:
  1. 异常处理FileOutputStream的构造函数和write()方法都可能抛出IOException。因此,你应该使用try-catch块来处理这些异常。
  2. 关闭流:在finally块中关闭流是一个好习惯,以确保即使在发生异常时也能关闭流。Java 7及更高版本引入了try-with-resources语句,它可以自动关闭实现了AutoCloseable接口的资源(如FileOutputStream)。
  3. 数据完整性:在写入大量数据到文件时,应该考虑使用缓冲区(如BufferedOutputStream)来提高性能。此外,确保在关闭流之前写入所有数据,以避免数据丢失。
  4. 文件路径和权限:确保指定的文件路径是有效的,并且你的程序有足够的权限来写入该文件。否则,你可能会遇到FileNotFoundExceptionSecurityException
  5. 编码问题:当写入字符串时,请注意字符编码。默认情况下,getBytes()方法使用平台的默认字符集进行编码。如果你需要特定的字符集(如UTF-8),请明确指定它,如data.getBytes("UTF-8")

BufferedOutputStream(高级流)

例题

例子1
package com.mohuanan.test;

import java.io.FileInputStream;
import java.io.IOException;

public class Demo05 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("b.txt");
        int b;
        while ((b = fis.read()) != -1) {
            System.out.print((char) b);
        }
    }
}
例子2(文件的拷贝)
package com.mohuanan.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo07 {
    public static void main(String[] args) throws IOException {


        //分别创建两个对象
        FileInputStream fis = new FileInputStream("C:\\Users\\17380\\Pictures\\网上的图片\\c5cc3ef5865b95b92ea88cecf3e9ad04.jpg");
        FileOutputStream fos = new FileOutputStream("test01.png");
        //核心思想 边读边写
        //创建一个字节数组
        byte[] bytes = new byte[1024*1024*1];

        int len;
        long start = System.currentTimeMillis();
        while ((len = fis.read(bytes)) != -1) {
            //b 代表fis文件里面的每一个字节
            fos.write(bytes,0,len);
        }
        //释放资源
        //先开的后关闭
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        fos.close();
        fis.close();
    }
}
例子3(//拷贝一个文件夹 考虑子文件夹)
package com.mohuanan.exercise;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        //拷贝一个文件夹 考虑子文件夹
        File inputFile = new File("D:\\marktext的文档");
        //FileInputStream fis = new FileInputStream(inputFile);
        File outputFile = new File("D:\\kaobei");
        //FileOutputStream fos = new FileOutputStream(outputFile);
        //调用方法
        copyDir(inputFile, outputFile);

    }

    /*
     * 参数一: 表示原来的文件
     * 参数二: 表示要拷贝到哪里的文件
     * 作用: 文件的拷贝
     * */
    public static void copyDir(File inputFile, File outputFile) throws IOException {
        outputFile.mkdirs();
        //1. 获取文件的数组
        File[] files = inputFile.listFiles();
        //2. 遍历数组
        for (File f : files) {
            if (f.isFile()) {
                //f是文件 拷贝 字节流
                FileInputStream fis = new FileInputStream(f);
                //子路径的名字
                String name = f.getName();
                FileOutputStream fos = new FileOutputStream(new File(outputFile, name));
                byte[] bytes = new byte[1024 * 1024 * 1];
                //记录长度
                int len;
                while ((len = fis.read(bytes)) != -1) {
                    //拷贝
                    fos.write(bytes, 0, len);
                }
                fos.close();
                fis.close();
            } else if (f.isDirectory()) {
                //f是文件夹
                //递归
                copyDir(f, new File(outputFile, f.getName()));
            }
        }
    }


}
例子4(修改文件里面的数据)

package com.mohuanan.exercise;



import java.io.*;
import java.util.Arrays;

public class Demo03 {
public static void main(String[] args) throws IOException {
//修改文件里面的数据
File f1 =new File("a.txt");
//1. 获取文件里面的数据
FileReader fr = new FileReader(f1);
int h;
StringBuilder sb = new StringBuilder();
while((h = fr.read()) !=-1){
sb.append((char) h);
}
//释放资源
fr.close();
String[] strArr = sb.toString().split("-");
//2. 进行排序
Integer[] array = Arrays.stream(strArr)
.map(Integer::parseInt)
.sorted()
.toArray(Integer[]::new);
//3. 进行写入
FileWriter fw = new FileWriter(f1);
String replace = Arrays.toString(array).replace(", ", "-");
String substring = replace.substring(1, replace.length() - 1);
fw.write(substring);
fw.close();

}


}

字符流

Reader(抽象类)

FileReader(基本流)
  • File作用

  • Reader: 他爸

package com.mohuanan.test;


import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Demo09 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileReader fr = new FileReader("a.txt");
        char[] chars = new char[10];
        int len;
        while((len = fr.read(chars)) != -1){
            String string = new String(chars, 0, len);
            System.out.print(string);

        }
        //释放资源
        fr.close();
    }
}
BufferedReader(高级流)
  • 底层自带了长度为8192的字节数组,即缓冲区

  • 字符输入缓冲流特有的方法readLine():读取一行数据,如果没有数据了,返回null

Writer(抽象类)

FileReader(基本流)
  • File作用

  • Writer: 他爸

package com.mohuanan.test;

import java.io.FileWriter;
import java.io.IOException;

public class Demo10 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileWriter fw = new FileWriter("a.txt",true);
        //进行写入
        fw.write("我爱你",1,2);
        fw.write("我爱你");
        //释放资源
        fw.close();
    }
}
BufferedWrite(高级流)
  • 字符缓冲输出流特有的方法newLine();跨平台的换行

Commons-io

在Java中,Commons-io是Apache软件基金会的一个项目,它提供了一组实用的IO(输入/输出)类和工具,用于简化Java的IO操作。具体来说,Commons-io包含了一系列的工具类,用于处理输入、输出流、文件操作等常见的IO操作,提供了更加简单、高效的IO操作方式,极大地简化了Java的IO编程。

Commons-io的主要用处包括:

  1. 文件操作:提供了一系列的方法,用于复制、移动、删除、重命名、比较文件等常见的文件操作。
  2. 流操作:提供了一系列的工具类,用于操作输入、输出流,如复制、关闭、转换、读取、写入等。
  3. 文件过滤:提供了一系列的过滤器,用于过滤文件,包括按文件名、文件大小、文件类型等进行过滤。
  4. 目录操作:提供了一系列的工具类,用于操作目录,如创建、删除、遍历目录等。

使用Commons-io,你可以通过引入相应的jar包,并在代码中调用相应的类和方法来实现具体的IO操作。以下是一些常用的Commons-io类和方法:

  • IOUtils类:这个类提供了很多静态方法来简化IO操作,例如IOUtils.copy(InputStream in, OutputStream out)方法用于复制输入流到输出流,IOUtils.closeQuietly(Closeable closeable)方法用于悄悄地关闭流,自动处理关闭时可能抛出的异常。
  • FileUtils类:这个类提供了很多静态方法来简化文件操作,例如FileUtils.copyFile(File srcFile, File destFile)方法用于复制文件,FileUtils.deleteQuietly(File file)方法用于悄悄地删除文件,自动处理删除时可能抛出的异常。
  • FilenameUtils类:这个类提供了很多静态方法来处理文件名,例如FilenameUtils.getBaseName(String filename)方法用于获取文件名(不包括扩展名),FilenameUtils.getExtension(String filename)方法用于获取文件的扩展名。

要使用Commons-io,你首先需要将其jar包添加到你的项目依赖中。如果你使用的是Maven,你可以在pom.xml文件中添加相应的依赖。然后,在你的Java代码中,你可以通过import语句引入相应的类,并调用其提供的方法来执行IO操作。

请注意,以上信息仅供参考,具体的使用方法和类名可能会因Commons-io的版本不同而有所差异。建议查阅官方文档或相关教程以获取更详细的信息。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,让我来详细讲解一下Java IO流的知识点。 Java IO(Input/Output)流是Java用于处理输入输出的机制。它提供了一种标准的方法来处理与文件、网络连接、管道等相关的操作。 Java IO流被分为两类:字节流和字符流。 - 字节流:以字节为单位进行读写操作,适用于二进制文件或以字节为基础的文本文件的读写操作。字节流主要包括InputStream和OutputStream两个类。 - 字符流:以字符为单位进行读写操作,适用于以字符为基础的文本文件的读写操作。字符流主要包括Reader和Writer两个类。 Java IO流的常用类有: 1. FileInputStream 和 FileOutputStream FileInputStream 和 FileOutputStream 是用于读写文件的字节流。FileInputStream 可以打开一个文件,读取其中的内容;FileOutputStream 可以打开一个文件,将内容写入文件中。示例代码如下: ```java try (FileInputStream fis = new FileInputStream("input.txt"); FileOutputStream fos = new FileOutputStream("output.txt")) { byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } ``` 2. FileReader 和 FileWriter FileReader 和 FileWriter 是用于读写文件的字符流。FileReader 可以打开一个文件,读取其中的内容;FileWriter 可以打开一个文件,将内容写入文件中。示例代码如下: ```java try (FileReader fr = new FileReader("input.txt"); FileWriter fw = new FileWriter("output.txt")) { char[] buffer = new char[1024]; int len; while ((len = fr.read(buffer)) != -1) { fw.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } ``` 3. ByteArrayInputStream 和 ByteArrayOutputStream ByteArrayInputStream 和 ByteArrayOutputStream 是用于读写内存中的字节流。ByteArrayInputStream 可以从一个字节数组中读取内容;ByteArrayOutputStream 可以将内容写入一个字节数组中。示例代码如下: ```java byte[] data = "Hello, world!".getBytes(); try (ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = bais.read(buffer)) != -1) { baos.write(buffer, 0, len); } byte[] result = baos.toByteArray(); System.out.println(new String(result)); } catch (IOException e) { e.printStackTrace(); } ``` 4. CharArrayReader 和 CharArrayWriter CharArrayReader 和 CharArrayWriter 是用于读写内存中的字符流。CharArrayReader 可以从一个字符数组中读取内容;CharArrayWriter 可以将内容写入一个字符数组中。示例代码如下: ```java char[] data = "Hello, world!".toCharArray(); try (CharArrayReader car = new CharArrayReader(data); CharArrayWriter caw = new CharArrayWriter()) { char[] buffer = new char[1024]; int len; while ((len = car.read(buffer)) != -1) { caw.write(buffer, 0, len); } char[] result = caw.toCharArray(); System.out.println(new String(result)); } catch (IOException e) { e.printStackTrace(); } ``` 5. BufferedReader 和 BufferedWriter BufferedReader 和 BufferedWriter 是用于带缓存的读写字符流。示例代码如下: ```java try (BufferedReader br = new BufferedReader(new FileReader("input.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } ``` 6. DataInputStream 和 DataOutputStream DataInputStream 和 DataOutputStream 是用于读写基本数据类型和字符串。示例代码如下: ```java try (DataInputStream dis = new DataInputStream(new FileInputStream("data.bin")); DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"))) { dos.writeInt(123); dos.writeUTF("Hello, world!"); int num = dis.readInt(); String str = dis.readUTF(); System.out.println(num + ", " + str); } catch (IOException e) { e.printStackTrace(); } ``` 7. ObjectInputStream 和 ObjectOutputStream ObjectInputStream 和 ObjectOutputStream 是用于读写Java对象。示例代码如下: ```java class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.bin")); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.bin"))) { Person p1 = new Person("Alice", 18); oos.writeObject(p1); Person p2 = (Person) ois.readObject(); System.out.println(p2); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } ``` Java IO流在处理文件、网络连接、管道等方面具有广泛的应用,是Java编程不可或缺的一部分。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值