使用StringReader和StringWriter操作字符串

编程举例:写一函数把StringReader中输入流中的字符串全部转换成大写,然后将结果写到一个StringWriter中,然后使用这一函数将以字符串全部转成大写。

 

package cn.itcast.stringstream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; public class StringStreamTest { public static void main(String[] args) { String str = "abcdefghijklmn"; transform(str); } public static void transform(String str) { StringReader sr = new StringReader(str); StringWriter sw = new StringWriter(); char[] chars = new char[1024]; try { int len = 0; while ((len = sr.read(chars)) != -1) { String strRead = new String(chars, 0, len).toUpperCase(); System.out.println(strRead); sw.write(strRead); sw.flush(); } sr.close(); sw.close(); } catch (IOException e) { e.printStackTrace(); } finally { sr.close(); try { sw.close(); } catch (IOException e) { e.printStackTrace(); } } } }

你可能感兴趣的:(JAVA)