Easy way to write contents of a Java InputStream to an OutputStream

后端 未结 23 2735
粉色の甜心
粉色の甜心 2020-11-22 02:10

I was surprised to find today that I couldn\'t track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviou

23条回答
  •  耶瑟儿~
    2020-11-22 03:03

    Using Java7 and try-with-resources, comes with a simplified and readable version.

    try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");
        OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {
    
        byte[] buffer = new byte[10*1024];
    
        for (int length; (length = inputStream.read(buffer)) != -1; ) {
            outputStream.write(buffer, 0, length);
        }
    } catch (FileNotFoundException exception) {
        exception.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    

提交回复
热议问题