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();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM