java中的FileInputStream三种read()函数用法

  

针对“java中的FileInputStream三种read()函数用法”,我整理了以下攻略:

一、FileInputStream简介

java.io包中的FileInputStream是一个类,它用于从文件系统中的文件获取输入字节流。它继承了InputStream类。在使用FileInputStream时,一个文件必须存在,并且应该以字节的形式存在。
FileInputStream类的构造函数有三种不同的方式,它们是:

public FileInputStream(File file) throws FileNotFoundException {} //使用文件路径构建FileInputStream对象
public FileInputStream(String path) throws FileNotFoundException {} //使用文件对象构建FileInputStream对象
public FileInputStream(FileDescriptor fdObj) {} //使用文件描述符对象构建FileInputStream对象

二、FileInputStream中的三种read()函数用法

FileInputStream类提供了三种不同的read()方法重载,它们可以读取多个字节数据并进行不同的处理。这三种read()方法是:

read()

public int read() throws IOException {}
  • 从输入的字节流中读取下一个字节,并返回该字节的值(0~255)。
  • 如果已经到达输入流的末尾,则返回-1。

示例1:

假设文件路径为"test.txt", 文件内容为:"Hello World!"。以下代码展示如何使用read()方法从文件中读取并输出文件中的内容:

FileInputStream fis = null;
try {
    fis = new FileInputStream("test.txt");
    int data = fis.read();
    while (data != -1) {
        System.out.print((char) data);  // 打印文件内容
        data = fis.read();  // 从输入流中读取新的字节
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        fis.close();  // 释放资源
    } catch (IOException e) {
        e.printStackTrace();
    }
}

输出结果如下:

Hello World!

read(byte[] b)

public int read(byte[] b) throws IOException {}
  • 从输入流中读取一定数量的字节,并将它们存储在数组b中。
  • 该方法返回读取的字节数。如果已经到达输入流的末尾,则返回-1。

示例2:

假设文件路径为"test.txt", 文件内容为:"Hello World!"。以下代码展示如何使用read(byte[] b)方法从文件中读取并输出文件中的内容:

FileInputStream fis = null;
try {
    fis = new FileInputStream("test.txt");
    byte[] buffer = new byte[1024];  // 数组大小为1024字节
    int length;
    while ((length = fis.read(buffer)) != -1) {
        System.out.write(buffer, 0, length);  // 打印读取的内容
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        fis.close();  // 释放资源
    } catch (IOException e) {
        e.printStackTrace();
    }
}

输出结果如下:

Hello World!

read(byte[] b, int off, int len)

public int read(byte[] b, int off, int len) throws IOException {}
  • 从输入流中读取最多len个字节,并将它们存储在数组b中,开始存储的位置是offset。
  • 该方法返回读取的字节数。如果已经到达输入流的末尾,则返回-1。

示例3:

假设文件路径为"test.txt", 文件内容为:"Hello World!"。以下代码展示如何使用read(byte[] b, int off, int len)方法从文件中读取并输出文件中的内容:

FileInputStream fis = null;
try {
    fis = new FileInputStream("test.txt");
    byte[] buffer = new byte[1024];  // 数组大小为1024字节
    int length = fis.read(buffer, 0, 5);  // 从输入流中读取5个字节
    String str = new String(buffer, 0, length, "UTF-8");
    System.out.println(str);  // 打印读取的内容
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        fis.close();  // 释放资源
    } catch (IOException e) {
        e.printStackTrace();
    }
}

输出结果如下:

Hello

通过以上三个示例,我们可以清楚地了解到FileInputStream的三种不同的read()函数用法。

相关文章