使用 FileInputStream 类可以将文件转换为字节流。以下是一个示例代码:

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

public class FileToByteStreamExample {
    public static void main(String[] args) {
        String filePath = 'C:\path\to\file.txt'; // 替换为实际文件的路径
        
        try {
            byte[] fileBytes = convertFileToBytes(filePath);
            // 在这里可以使用字节流进行进一步的操作
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] convertFileToBytes(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileBytes = new byte[(int) file.length()];

        try (InputStream inputStream = new FileInputStream(file)) {
            inputStream.read(fileBytes);
        }

        return fileBytes;
    }
}

在上面的代码中,convertFileToBytes 方法接收文件的本地路径作为参数,并返回一个字节数组。它首先创建一个 File 对象,然后创建一个与文件关联的 FileInputStream 对象。使用 FileInputStream 对象的 read 方法将文件的内容读取到字节数组中。最后,返回字节数组。

请注意,上述代码中使用了 try-with-resources 语句来确保在读取文件后正确关闭输入流。这是一种简化的写法,可以自动处理资源的关闭。

Java 将文件转换为字节流:简单指南和代码示例

原文地址: https://www.cveoy.top/t/topic/p6Kd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录