Java InputStream、String、File相互转化

来源:互联网 发布:网络建设质量的重要性 编辑:程序博客网 时间:2024/05/04 01:51


转自:http://blog.sina.com.cn/s/blog_a000da9d010121bl.html

String --> InputStream
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());

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


File --> InputStream

InputStream in = new FileInputStream(file);

 

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

0 0