經過:今天在用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.至於上面那段代碼為什么會出現亂碼,暫時還未研究出來