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

后端 未结 23 2452
粉色の甜心
粉色の甜心 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:05

    A IMHO more minimal snippet (that also more narrowly scopes the length variable):

    byte[] buffer = new byte[2048];
    for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    

    As a side note, I don't understand why more people don't use a for loop, instead opting for a while with an assign-and-test expression that is regarded by some as "poor" style.

提交回复
热议问题