您好,登錄后才能下訂單哦!
InputStream,String,File相互轉化
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(); }
今天從網上看到了另一種方法,特拿來分享
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(); }
此兩種方法上面一種更快,但是比較耗內存,后者速度慢,耗資源少
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(); }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。