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

