如何将 Java 文件转换为 InputStream?这两种方法很管用!

简介: 【1月更文挑战第7天】

在 Java 中,我们通常使用流(Stream)来在文件和程序之间传输数据。而在某些情况下,我们需要将一个 Java 文件转换为 InputStream 对象,以便进行操作或传输。

本文将介绍如何将 Java 文件转换为 InputStream 对象,并给出多个实用的例子。

方法一:使用 FileInputStream

最常见的将 Java 文件转换为 InputStream 的方法是使用 FileInputStream 类。该类提供了一些方法来读取文件的内容,并返回 InputStream 对象。

以下是一个示例代码,展示如何使用 FileInputStream 读取文件并返回 InputStream 对象:

import java.io.*;

public class FileToInputStreamExample {
   
   
    public static InputStream fileToInputStream(String filePath) throws IOException {
   
   
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        return fileInputStream;
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            InputStream inputStream = fileToInputStream("example.txt");
            // do something with inputStream
            inputStream.close();
        } catch (IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

上述代码中,我们使用 File 类和 FileInputStream 类创建一个 FileInputStream 对象,并返回相应的 InputStream 对象。

方法二:使用 ClassLoader.getResourceAsStream

另一种将文件转换为 InputStream 的方法是使用 ClassLoader.getResourceAsStream 方法。该方法可以从类路径中获取指定的资源,并返回一个 InputStream 对象。

以下是一个示例代码,展示如何使用 ClassLoader.getResourceAsStream 获取文件并返回 InputStream 对象:

import java.io.*;

public class FileToInputStreamExample {
   
   
    public static InputStream fileToInputStream(String filePath) throws IOException {
   
   
        InputStream inputStream = FileToInputStreamExample.class.getClassLoader().getResourceAsStream(filePath);
        return inputStream;
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            InputStream inputStream = fileToInputStream("example.txt");
            // do something with inputStream
            inputStream.close();
        } catch (IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

上述代码中,我们使用 ClassLoader.getResourceAsStream 来获取文件,并返回相应的 InputStream 对象。

示例

现在,我们来看一些将 Java 文件转换为 InputStream 的实用例子。

示例一:从URL获取图片并转换为InputStream

以下示例代码展示了如何从 URL 获取图片并将其转换为 InputStream 对象:

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class FileToInputStreamExample {
   
   
    public static InputStream urlToInputStream(String url) throws IOException {
   
   
        URLConnection connection = new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.connect();
        return connection.getInputStream();
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            InputStream inputStream = urlToInputStream("https://example.com/image.jpg");
            // do something with inputStream
            inputStream.close();
        } catch (IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

示例二:将文件转换为字节数组

以下示例代码展示了如何将文件转换为字节数组:

import java.io.*;

public class FileToInputStreamExample {
   
   
    public static byte[] fileToByteArray(String filePath) throws IOException {
   
   
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fileInputStream.read(bytes);
        fileInputStream.close();
        return bytes;
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            byte[] bytes = fileToByteArray("example.txt");
            // do something with bytes
        } catch (IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

示例三:从InputStream读取文件内容

以下示例代码展示了如何从 InputStream 中读取文件的内容:

import java.io.*;

public class FileToInputStreamExample {
   
   
    public static void readInputStream(InputStream inputStream) throws IOException {
   
   
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        while ((line = reader.readLine()) != null) {
   
   
            System.out.println(line);
        }
        reader.close();
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            InputStream inputStream = fileToInputStream("example.txt");
            readInputStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

示例四:使用JAXB从XML文件获取对象

以下示例代码展示了如何使用 JAXB 从 XML 文件获取对象:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;

public class FileToInputStreamExample {
   
   
    public static Object xmlToObject(String filePath, Class<?> clazz) throws JAXBException, IOException {
   
   
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        InputStream inputStream = new FileInputStream(filePath);
        Object object = unmarshaller.unmarshal(new BufferedReader(new InputStreamReader(inputStream)));
        inputStream.close();
        return object;
    }

    public static void main(String[] args) {
   
   
        try {
   
   
            Object object = xmlToObject("example.xml", Example.class);
            // do something with object
        } catch (JAXBException | IOException e) {
   
   
            e.printStackTrace();
        }
    }
}

以上就是几个将 Java 文件转换为 InputStream 的实用例子,其中包括从 URL 获取图片并转换为 InputStream 对象、将文件转换为字节数组、从 InputStream 中读取文件内容和使用 JAXB 从 XML 文件获取对象。通过这些例子,相信您已经掌握了如何将 Java 文件转换为 InputStream 的方法,并且可以在实际开发中使用它们。

目录
相关文章
|
1月前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
31 1
|
1月前
|
Java
java中替换文件内容
java中替换文件内容
14 1
|
17天前
|
Java
Java中ReentrantLock中tryLock()方法加锁分析
Java中ReentrantLock中tryLock()方法加锁分析
13 0
|
1月前
|
Java
java中日期处理的一些工具方法
java中日期处理的一些工具方法
18 1
|
6天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
33 3
|
1天前
|
存储 前端开发 Java
Java实现文件分片上传
Java实现文件分片上传
6 0
|
3天前
|
Java
Java 与垃圾回收有关的方法
Java 与垃圾回收有关的方法
|
4天前
|
存储 Java 测试技术
一文搞清楚Java中的方法、常量、变量、参数
在JVM的运转中,承载的是数据,而数据的一种变现形式就是“量”,量分为:**常量与变量**,我们在数学和物理学中已经接触过变量的概念了,在Java中的变量就是在程序运行过程中可以改变其值的量。
14 0
|
8天前
|
存储 Java
Java动态转发代理IP的实现方法
Java动态转发代理IP的实现方法
23 11
|
9天前
|
Java
Java接口中可以定义哪些方法?
【4月更文挑战第13天】
14 0
Java接口中可以定义哪些方法?