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

后端 未结 23 2497
粉色の甜心
粉色の甜心 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
    2020-11-22 02:45

    public static boolean copyFile(InputStream inputStream, OutputStream out) {
        byte buf[] = new byte[1024];
        int len;
        long startTime=System.currentTimeMillis();
    
        try {
            while ((len = inputStream.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
    
            long endTime=System.currentTimeMillis()-startTime;
            Log.v("","Time taken to transfer all bytes is : "+endTime);
            out.close();
            inputStream.close();
    
        } catch (IOException e) {
    
            return false;
        }
        return true;
    }
    

提交回复
热议问题