InputStream,String,File相互轉化
創(chuàng)新互聯(lián)公司是一家網(wǎng)站建設、成都做網(wǎng)站,提供網(wǎng)頁設計,網(wǎng)站設計,網(wǎng)站制作,建網(wǎng)站,按需開發(fā),網(wǎng)站開發(fā)公司,于2013年成立是互聯(lián)行業(yè)建設者,服務者。以提升客戶品牌價值為核心業(yè)務,全程參與項目的網(wǎng)站策劃設計制作,前端開發(fā),后臺程序制作以及后期項目運營并提出專業(yè)建議和思路。
1. String --> InputStream
InputStream String2InputStream(String str){ ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes()); return stream; }
2. InputStream --> String
String inputStream2String(InputStream is){ BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null){ buffer.append(line); } return buffer.toString(); }
今天從網(wǎng)上看到了另一種方法,特拿來分享
String all_content=null; try { all_content =new String(); InputStream ins = 獲取的輸入流; ByteArrayOutputStream outputstream = new ByteArrayOutputStream(); byte[] str_b = new byte[1024]; int i = -1; while ((i=ins.read(str_b)) > 0) { outputstream.write(str_b,0,i); } all_content = outputstream.toString(); } catch (Exception e) { e.printStackTrace(); }
此兩種方法上面一種更快,但是比較耗內(nèi)存,后者速度慢,耗資源少
3、File --> InputStream
InputStream in = new InputStream(new FileInputStream(File));
4、InputStream --> File
public void inputstreamtofile(InputStream ins,File file){ OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!