The mutual transformation and comparison between InputStream String and File in java
- 2020-06-19 10:27:15
- OfStack
InputStream,String,File convert to each other
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();
}
Today From the Internet to see another way to share
String all_content=null;
try {
all_content =new String();
InputStream ins = Gets the input stream ;
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();
}
The first of these two methods is faster, but more memory consumption, the latter is slower, less resource consumption
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();
}
Thank you for reading, I hope to help you, thank you for your support to this site!