Java InputStream转File

  • 文件处于磁盘上或者流处于内存中
在输入流有已知的和预处理的数据时,如在硬盘上的文件或者在流处于内存中。这种情况下,不需要做边界校验,并且内存容量条件允许的话,可以简单的读取并一次写入。
InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
 
File targetFile = new File("src/main/resources/targetFile.tmp");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer); 
 
基于Guava的实现
InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File targetFile = new File("src/main/resources/targetFile.tmp");
Files.write(buffer, targetFile);

 

基于Commons IO的实现
InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
File targetFile = new File("src/main/resources/targetFile.tmp");
FileUtils.copyInputStreamToFile(initialStream, targetFile);

 

  • 输入流映射正在进行的数据流
如果输入流链接到正在进行的数据流上,如来自正在进行的链接的HTTP响应,此时可能无法一次读取整个流。这种情况下,我们需要确保一直读取到流的尽头。
File targetFile = new File("src/main/resources/targetFile.tmp");
try(InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
    OutputStream outStream = new FileOutputStream(targetFile)) {
    byte[] buffer = new byte[8 * 1024];
    int bytesRead;
    while ((bytesRead = initialStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }
} catch (Exception e) {
    e.printStackTrace();
}

 

另一种实现方式:
try (InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"))) {
    File targetFile = new File("src/main/resources/targetFile.tmp");
 
    java.nio.file.Files.copy(
            initialStream,
            targetFile.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
    e.printStackTrace();
}

 

posted @ 2018-05-21 09:15  飞昂之雪  阅读(149461)  评论(2编辑  收藏  举报