java 中InputStream,String,File之間的相互轉(zhuǎn)化對(duì)比
InputStream,String,File相互轉(zhuǎn)化
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)上看到了另一種方法,特拿來(lái)分享
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(); }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
- Java使用FileInputStream流讀取文件示例詳解
- 詳解FileInputStream讀取文件數(shù)據(jù)的兩種方式
- Java中的FileInputStream 和 FileOutputStream 介紹_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別
- Android 數(shù)據(jù)存儲(chǔ)之 FileInputStream 工具類及FileInputStream類的使用
- Java FileInputStream讀中文亂碼問題解決方案
相關(guān)文章
解決springboot報(bào)錯(cuò)Failed?to?parse?multipart?servlet?request
在使用SpringBoot開發(fā)時(shí),通過Postman發(fā)送POST請(qǐng)求,可能會(huì)遇到因臨時(shí)目錄不存在而導(dǎo)致的MultipartException異常,這通常是因?yàn)镺S系統(tǒng)(如CentOS)定期刪除/tmp目錄下的臨時(shí)文件,解決方案包括重啟項(xiàng)目2024-10-10Spring Boot集成ShedLock分布式定時(shí)任務(wù)的實(shí)現(xiàn)示例
ShedLock確保您計(jì)劃的任務(wù)最多同時(shí)執(zhí)行一次。如果一個(gè)任務(wù)正在一個(gè)節(jié)點(diǎn)上執(zhí)行,則它會(huì)獲得一個(gè)鎖,該鎖將阻止從另一個(gè)節(jié)點(diǎn)(或線程)執(zhí)行同一任務(wù)。2021-05-05安卓系統(tǒng)中實(shí)現(xiàn)搖一搖畫面振動(dòng)效果的方法
這篇文章主要介紹了安卓系統(tǒng)中實(shí)現(xiàn)搖一搖畫面振動(dòng)效果的方法,調(diào)用Android SDK中的SensorEventListener接口,需要的朋友可以參考下2015-07-07Java多線程導(dǎo)致CPU占用100%解決及線程池正確關(guān)閉方式
1000萬(wàn)表數(shù)據(jù)導(dǎo)入內(nèi)存數(shù)據(jù)庫(kù),按分頁(yè)大小10000查詢,多線程,15條線程跑,最后發(fā)現(xiàn)CPU占用100%卡死,那么如何解決,本文就來(lái)介紹一下,感興趣的朋友可以了解一下2021-05-05淺談讓@Value更方便的Spring自定義轉(zhuǎn)換類
Spring為大家內(nèi)置了不少開箱即用的轉(zhuǎn)換類,如字符串轉(zhuǎn)數(shù)字、字符串轉(zhuǎn)時(shí)間等,但有時(shí)候需要使用自定義的屬性,則需要自定義轉(zhuǎn)換類了2021-06-06在Java內(nèi)存模型中測(cè)試并發(fā)程序代碼
這篇文章主要介紹了在Java內(nèi)存模型中測(cè)試并發(fā)程序代碼,輔以文中所提到的JavaScript庫(kù)JCStress進(jìn)行,需要的朋友可以參考下2015-07-07