Java –将文件转换为InputStream

Java – Convert File to InputStream

1.概述

在本快速教程中,我们将展示如何将文件转换为InputStream –首先使用纯Java,然后使用Guava和Apache Commons IO库。

本文是Baeldung上的" Java – Back to Basic"系列的一部分。

进一步阅读:

Java扫描仪

番石榴–写入文件,从文件读取

Java字节数组到InputStream

2.使用Java进行转换

我们可以使用Java的IO包将File转换为不同的InputStreams。

2.1。 FileInputStream

让我们从第一个也是最简单的一个开始-使用FileInputStream:

1
2
3
4
5
6
@Test
public void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect()
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = new FileInputStream(initialFile);
}

2.2。数据输入流

让我们看另一个,在这里我们可以使用DataInputStream从文件中读取二进制或原始数据:

1
2
3
4
5
6
7
@Test
public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect()
  throws IOException {
      final File initialFile = new File("src/test/resources/sample.txt");
      final InputStream targetStream =
        new DataInputStream(new FileInputStream(initialFile));
}

2.3.SequenceInputStream

最后,让我们看一下如何使用SequenceInputStream将两个文件的输入流连接到singleInputStream:

1
2
3
4
5
6
7
8
9
10
11
@Test
public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect()
  throws IOException {
      final File initialFile = new File("src/test/resources/sample.txt");
      final File anotherFile = new File("src/test/resources/anothersample.txt");
      final InputStream targetStream = new FileInputStream(initialFile);
      final InputStream anotherTargetStream = new FileInputStream(anotherFile);
   
      InputStream sequenceTargetStream =
        new SequenceInputStream(targetStream, anotherTargetStream);
}

请注意,为了清晰起见,我们不会在这些示例中关闭结果流。

3.使用番石榴转换

接下来–让我们看一下使用中间字节源的Guava解决方案:

1
2
3
4
5
6
@Test
public void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect()
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = Files.asByteSource(initialFile).openStream();
}

4.使用Commons IO进行转换

最后,让我们看一下使用Apache Commons IO的解决方案:

1
2
3
4
5
6
@Test
public void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect()
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = FileUtils.openInputStream(initialFile);
}

在那里,您将获得3个简单而干净的解决方案,用于从Java文件打开流。

5.结论

在本文中,我们探讨了如何使用不同的库将文件转换为InputStream的各种方法。
所有这些示例和代码段的实现都可以在GitHub上找到-这是一个基于Maven的项目,因此应该很容易直接导入和运行。