欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 中InputStream,String,File之间的相互转化对比

程序员文章站 2024-03-02 20:32:52
inputstream,string,file相互转化  1. string --> inputstream inputstream s...

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!