字符流:尽管字节流提供了处理任何类型输入/输出操作的足够功能,它们补鞥呢直接操作Unicode字符。字符流层次结构的顶层是Reader和Writer抽象类。类似于InputStream和OutputStram
Unicode使用两个字节来表示一个字符,即一个字符占16位
一、Reader的类层次结构
二、Writer的类层次结构
三、Demo
public class StreamTest { public static void main(String[] args) throws Exception{
FileOutputStream fos = new FileOutputStream("D:/temp/file.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write("http://www.baidu.com");
bw.newLine();
bw.write("http://www.googlo.com");
bw.close(); FileInputStream fis = new FileInputStream("D:/temp/file.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String str = null;
while ((str = br.readLine() ) != null) {
System.out.println(str); } br.close(); }
}
文本的内容
打印出的输出
四、Demo2 标准输入设备
//标准输入设备
public class StreamTest2 { public static void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str ;
while (null != (str = br.readLine())) {
System.out.println(str); }
br.close(); }
}
显示效果
五、FileReader使用,
从一个文件逐行读取帮把它输出到标准输出流。
public class FileReader1 { public static void main(String[] args) throws Exception{
FileReader fr = new FileReader("D:/temp/hello.txt");
BufferedReader br = new BufferedReader(fr);
String str ;
while((str = br.readLine()) != null ){
System.out.println(str);
}
br.close(); }
}
FileWriter使用
public class FileWriter1 {
public static void main(String[] args) throws Exception { String str = "hello world , Hello world";
char[] buffer = new char[str.length()];
str.getChars(0, str.length(), buffer, 0); FileWriter fw = new FileWriter("D:/temp/fileWrite.txt");
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < buffer.length ; i++){
bw.write(buffer[i]);
}
bw.close(); }
}
写入结果
六、CharArrayReader使用
public class charArrayReader1 { public static void main(String[] args) throws Exception{
String tmp = "hello world, HI";
char[] ch = new char[tmp.length()];
tmp.getChars(0, tmp.length(), ch, 0); CharArrayReader fr = new CharArrayReader(ch);
BufferedReader br = new BufferedReader(fr);
String str ;
while((str = br.readLine()) != null ){
System.out.println(str);
}
br.close(); }
}