现在的位置: 首页 > 综合 > 正文

InputStream,String,File相互转化

2012年09月18日 ⁄ 综合 ⁄ 共 784字 ⁄ 字号 评论关闭

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();
}

3、File --> InputStream
InputStream in = new InputStream(new FileInputStream(File));

上面这行报错,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();
}

抱歉!评论已关闭.