[Java] Download file without saving

Source:

CSDN: InputStream类available和read方法可能读取不到完整的流数据

stackoverflow: How to read a http file inmemory without saving on local drive?

private static InputStream download(String sourceURL) throws Exception {
        InputStream inputStream = new URL(sourceURL).openStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = inputStream.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return new ByteArrayInputStream(output.toByteArray());
}
This entry was posted in Java. Bookmark the permalink.