如何使用FileInputStream读取文件数据?
FileInputStream类从特定文件读取数据(逐字节)。它通常用于读取包含原始字节的文件内容,例如图像。
要使用此类读取文件内容:
- 首先,需要通过传递一个String变量或一个**File**对象来实例化此类,该对象表示要读取文件的路径。
FileInputStream inputStream = new FileInputStream("file_path");
or,
File file = new File("file_path");
FileInputStream inputStream = new FileInputStream(file);- 然后使用**read()**方法的任何变体读取指定文件的内容:
**int read()** - 这只是从当前InputStream读取数据并逐字节返回读取的数据(以整数格式)。
如果达到文件末尾,此方法返回-1。
**int read(byte[] b)** - 此方法接受一个字节数组作为参数,并将当前InputStream的内容读取到给定的数组中。
此方法返回一个整数,表示字节总数,如果达到文件末尾则返回-1。
- **int read(byte[] b, int off, int len)** - 此方法接受一个字节数组、其偏移量(int)和长度(int)作为参数,并将当前InputStream的内容读取到给定的数组中。
- 此方法返回一个整数,表示字节总数,如果达到文件末尾则返回-1。
示例
假设我们在**D:/images**目录下有以下图像

下面的程序使用**FileInputStream**读取上述图像的内容。
示例
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String args[]) throws IOException {
//Creating a File object
File file = new File("D:/images/javafx.jpg");
//Creating a FileInputStream object
FileInputStream inputStream = new FileInputStream(file);
//Creating a byte array
byte bytes[] = new byte[(int) file.length()];
//Reading data into the byte array
int numOfBytes = inputStream.read(bytes);
System.out.println("Data copied successfully...");
}
}输出
Data copied successfully...
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP