使用ByteArrayOutputStream解决IO乱码问题的踩坑记录

经过:今天在用s3接口做ceph储存的时候,要实现一个io下载的接口。需要把InputStream转成byte[],一开始,是的写法是这样的:

        byte[] buf = new byte[(int) fileSize];
        InputStream in = ossObject.getObjectContent();
        try {
            for (int n = 0; n != -1; ) {
                n = in.read(buf, 0, buf.length);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }

        }

可是下载的文件稍大一些,就会出现乱码。于是换了网上推荐的,使用byte缓存的方法,来实现InputStream转成byte[]:

    private static byte[] inputToByte(InputStream inStream, int fileSize) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[fileSize];
        int rc;
        while ((rc = inStream.read(buff, 0, fileSize)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }

乱码的情况就解决了

总结:

  IO这块不是很熟悉,尽量不要用原生的方法去写,而应该使用JDK封装好的方法去实现。避免出现一些意料之外的问题。

PS.至于上面那段代码为什么会出现乱码,暂时还未研究出来

猜你喜欢

转载自www.cnblogs.com/xujanus/p/9842799.html