您的位置:

Java InputStream

一、InputStream 概述

InputStream 是 Java 中输入流的抽象类,它是字节输入流的父类,实现者必须定义 read() 方法,以便从输入流中读取字节。InputStream 在读取数据时,按照字节为单位从输入流中读取数据,并返回读取的数据。

InputStream 类的常用方法如下:

public abstract int read() throws IOException;
public int read(byte[] b) throws IOException;
public int read(byte[] b, int off, int len) throws IOException;
public long skip(long n) throws IOException;
public int available() throws IOException;
public void close() throws IOException;
public synchronized void mark(int readlimit);
public synchronized void reset() throws IOException;
public boolean markSupported();

其中,常用的方法有:

  • read():读取输入流中的字节,返回读取的字节码;
  • read(byte[] b):将输入流中的字节读入到字节数组中 b,返回读入的字节数量;
  • read(byte[] b, int off, int len):将输入流中的字节的 len 个读入到字节数组 b 中,从字节数组的 off 位置开始存储,返回读入的字节数量;
  • skip(long n):从输入流中跳过 n 个字节的数据;
  • available():返回输入流中还未读入的字节数;
  • close():关闭输入流的实例。

二、InputStream 的子类

1. FileInputStream

FileInputStream 是 InputStream 子类之一,它从文件中读取数据。FileInputStream 可以接受文件路径或 File 对象,读取指定文件。

示例代码:

File file = new File("test.txt");
InputStream inputStream = new FileInputStream(file);

int data;
while ((data = inputStream.read()) != -1) {
    System.out.print((char)data);
}

inputStream.close();
2. ByteArrayInputStream

ByteArrayInputStream 是 InputStream 的另一个子类,它可以从字节数组中读取数据。使用 ByteArrayInputStream 时,需要将要读取的字节数组传递给 ByteArrayInputStream 的构造函数。

示例代码:

byte[] byteArray = "Hello, world!".getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArray);

int data;
while ((data = inputStream.read()) != -1) {
    System.out.print((char)data);
}

inputStream.close();

三、InputStream 的使用注意事项

1. InputStream 的关闭

在读取完毕数据后,需要关闭 InputStream,否则资源无法释放。使用 try-with-resources 语句可以在读取完毕后自动关闭 InputStream。

示例代码:

File file = new File("test.txt");

try (InputStream inputStream = new FileInputStream(file)) {
    int data;
    while ((data = inputStream.read()) != -1) {
        System.out.print((char)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}
2. 字符集(Charset)的指定

在将 InputStream 中的字节转换为字符时,需要指定字符集以避免乱码问题。Java 中常见的字符集有 UTF-8、GBK、ISO8859-1 等。

示例代码:

File file = new File("test.txt");

try (InputStream inputStream = new FileInputStream(file);
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
    int data;
    while ((data = inputStreamReader.read()) != -1) {
        System.out.print((char)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}
3. 缓冲区(Buffer)的使用

在读取大文件时,可以通过使用缓冲区来提高读取速度。

示例代码:

File file = new File("large_file.txt");

try (InputStream inputStream = new FileInputStream(file);
     BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
    int data;
    while ((data = bufferedInputStream.read()) != -1) {
        System.out.print((char)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

四、小结

InputStream 是 Java 中输入流的抽象类,通过不同的子类对不同来源(如文件、字节数组)的输入流进行操作。在使用 InputStream 时,需要注意数据的关闭、字符集的指定以及缓冲区的使用。