• 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();
    }
  • 相关阅读:
    POJ 3630 Phone List | Trie 树
    POJ 3974 Palindrome | 马拉车模板
    POJ 3422 Kaka's Matrix Travels | 最小费用最大流
    POJ 2195 Going Home | 带权二分图匹配
    POJ 3068 "Shortest" pair of paths | 最小费用最大流
    POJ 3686 The Windy's | 最小费用最大流
    洛谷 最小费用最大流 模板 P3381
    POJ 2987 Firing | 最大权闭合团
    POJ 3469 Dual Core CPU | 最小割
    POJ 3281 Dining | 最大流
  • 原文地址:https://www.cnblogs.com/asfeixue/p/9065681.html
Copyright © 2020-2023  润新知