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();
}
跟大家说一下,这样的InputStream需要从文本文件(即纯文本的数据文件)中读取内容,然后将它的内容读出到一个String对象中。下面直接给出代码:
ackage cn.jcourse.example.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class StreamToString {
public static void main(String[] args) {
StreamToString sts = new StreamToString();
/*
* Get input stream of our data file. This file can be in the root of
* you application folder or inside a jar file if the program is packed
* as a jar.
*/
InputStream is = sts.getClass().getResourceAsStream("/data.txt");
/*
* Call the method to convert the stream to string
*/
System.out.println(sts.convertStreamToString(is));
}
public String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
如果大家学习过JavaIO部分的API,相信大家对上面的代码应该比较容易理解。我大致的讲解下,主要讲解convertStreamToString方法,它是主要的转换方法。我们首先将InputStream转换为BufferedReader对象,该对象用于读取文本。然后我们就一行行的读取文本数据并加入到StringBuilder中(这里也可以用StringBuffer对象)。这里主要主意的地方是while的结束条件是当读取到的字符串为null。然后在最后将StringBuilder对象转换为字符串返回回去。