将Java InputStream的内容写入OutputStream的简单方法

506

今天我惊讶地发现,在Java中找不到将InputStream的内容写入OutputStream的简单方式。显然,字节缓冲区代码并不难编写,但我认为我可能只是错过了一些可以使我的生活更轻松(并且代码更清晰)的东西。

那么,对于给定的InputStream inOutputStream out,是否有更简单的方法来编写以下内容呢?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

1
你在评论中提到这是为移动应用程序而设计的。它是原生的Android吗?如果是,让我知道,我会发布另一个答案(在Android中可以用一行代码完成)。 - Jabari
24个回答

0

我使用了 ByteStreamKt.copyTo(src, dst, buffer.length) 方法

这是我的代码

public static void replaceCurrentDb(Context context, Uri newDbUri) {
    try {
        File currentDb = context.getDatabasePath(DATABASE_NAME);
        if (currentDb.exists()) {
            InputStream src = context.getContentResolver().openInputStream(newDbUri);
            FileOutputStream dst = new FileOutputStream(currentDb);
            final byte[] buffer = new byte[8 * 1024];
            ByteStreamsKt.copyTo(src, dst, buffer.length);
            src.close();
            dst.close();
            Toast.makeText(context, "SUCCESS! Your selected file is set as current menu.", Toast.LENGTH_LONG).show();
        }
        else
            Log.e("DOWNLOAD:::: Database", " fail, database not found");
    }
    catch (IOException e) {
        Toast.makeText(context, "Data Download FAIL.", Toast.LENGTH_LONG).show();
        Log.e("DOWNLOAD FAIL!!!", "fail, reason:", e);
    }
}

-1
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;
}

5
请问您能否解释一下为什么这是正确答案? - rfornal

-1

-7

你可以使用这个方法

public static void copyStream(InputStream is, OutputStream os)
 {
     final int buffer_size=1024;
     try
     {
         byte[] bytes=new byte[buffer_size];
         for(;;)
         {
           int count=is.read(bytes, 0, buffer_size);
           if(count==-1)
               break;
           os.write(bytes, 0, count);
         }
     }
     catch(Exception ex){}
 }

6
catch(Exception ex){}翻译为:捕获(Exception ex)异常。这是一句顶级代码。 - ᄂ ᄀ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接