1. 經過OutputStream將字符類的數據輸出到Stringhtml
有些接口的入參是OutputStream, 若是經過這樣的接口將數據寫入到一個String中, 能夠這樣操做java
ByteArrayOutputStream out = new ByteArrayOutputStream(); print(out); //輸出到out out.toString();//轉換成String
2. 將OutputString封裝成Writer來實現更豐富的操做apache
ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer1 = new OutputStreamWriter(out);//最基本的方式 PrintStream writer2 = new PrintStream(out); //更加豐富的接口, 日常使用的System.out就是這個類型
3. 將Writer封裝成OutputStreamapi
JDK中好像有相關的接口, 可是apache的commons-io實現了, WriterOutputStream安全
4. 從InputStream讀取String性能
public static String readString(InputStream in) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i; while ((i = in.read()) != -1) { baos.write(i); } return baos.toString(); }
5. 將String封裝成Reader線程
String input = "java -jar xx.jar -a param_a"; StringReader reader = new StringReader(input); CharArrayReader reader2 = new CharArrayReader(input.toCharArray()); BufferedReader reader3 = new BufferedReader(reader); //能夠實現按行讀
6. 將InputStream封裝成Readercode
FileInputStream fin = new FileInputStream("xxx.txt"); InputStreamReader reader0 = new InputStreamReader(fin); FileReader reader1 = new FileReader("xxx.txt"); //直接將文件封裝成reader
7. 將Reader封裝成InputStreamhtm
使用apache的commons-io庫, ReaderInputStream接口
8. StringWriter與CharArrayWriter的區別
StringWriter是對StringBuffer的再次封裝, 它是線程安全的
CharArrayWriter所有是它本身實現的, 沒有藉助其它的類, 它也是線程安全的
兩者在性能上也沒有太大的差異, CharArrayWriter效率比StringBuffer高那麼一丁點兒, 正常狀況下, 看不出差異.
使用CharArrayWriter的惟一的好處可能就是獲取char[]比較方便, 它有現成的接口.