java 中InputStream,String,File之間的相互轉化對比
更新時間:2017年04月08日 10:49:12 作者:Rain
這篇文章主要介紹了java 中InputStream,String,File之間的相互轉化對比的相關資料,需要的朋友可以參考下
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();
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
如何使用Playwright對Java API實現(xiàn)自動視覺測試
這篇文章主要介紹了如何使用Playwright對Java API實現(xiàn)自動視覺測試,幫助大家更好的理解和使用Playwright,感興趣的朋友可以了解下2021-01-01
Java之while與do-while循環(huán)的用法詳解
在上一篇文章中,給大家講解了循環(huán)的概念,并重點給大家講解了for循環(huán)的使用。但在Java中,除了for循環(huán)之外,還有while、do-while、foreach等循環(huán)形式。這篇文章給大家講解while循環(huán)的使用2023-05-05

