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

后端 未结 23 2443
粉色の甜心
粉色の甜心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:52

    If you are using Java 7, Files (in the standard library) is the best approach:

    /* You can get Path from file also: file.toPath() */
    Files.copy(InputStream in, Path target)
    Files.copy(Path source, OutputStream out)
    

    Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath() to get path from file.

    To write into an existing file (e.g. one created with File.createTempFile()), you'll need to pass the REPLACE_EXISTING copy option (otherwise FileAlreadyExistsException is thrown):

    Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)
    

提交回复
热议问题