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)上看到了另一種方法,特拿來分享
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)文章
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(50)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-08-08
如何使用Playwright對(duì)Java API實(shí)現(xiàn)自動(dòng)視覺測(cè)試
這篇文章主要介紹了如何使用Playwright對(duì)Java API實(shí)現(xiàn)自動(dòng)視覺測(cè)試,幫助大家更好的理解和使用Playwright,感興趣的朋友可以了解下2021-01-01
Java之while與do-while循環(huán)的用法詳解
在上一篇文章中,給大家講解了循環(huán)的概念,并重點(diǎn)給大家講解了for循環(huán)的使用。但在Java中,除了for循環(huán)之外,還有while、do-while、foreach等循環(huán)形式。這篇文章給大家講解while循環(huán)的使用2023-05-05
Mybatis中的游標(biāo)查詢Cursor(滾動(dòng)查詢)
這篇文章主要介紹了Mybatis中的游標(biāo)查詢Cursor(滾動(dòng)查詢),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
idea中怎樣創(chuàng)建并運(yùn)行第一個(gè)java程序
這篇文章主要介紹了idea中怎樣創(chuàng)建并運(yùn)行第一個(gè)java程序問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
springboot配置文件綁定實(shí)現(xiàn)解析
這篇文章主要介紹了springboot配置文件綁定實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01

