Java IO之字符流
前面总结了字节流,现在总节一下字符流。
什么是字符流,简单来说字符流就是 字节流+编码表;
字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串。字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的。字符流操作的是缓冲区(当我们对文件进行读写操作时如果不调用close() 或 flush()方法时不能看到数据的变化)。
既然是基于字节流,那么一样分为输出流和输入流
1.
输出流 OutputStreamWriter:
构造方法如下:
字符流的写入方式(可以字节输入一个字符串):
接着是输入流InputStreamReader:
构造方法有:
例子:
例子:
public static void main(String[] args) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(new FileInputStream("osw2.txt"),"UTF-8");
char[] chs = new char[1024];
int len = 0;
while((len=isr.read(chs))!=-1){
System.out.println(new String(chs,0,len));
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(isr!=null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
例子:
public static void main(String[] args) {
FileReader fr =null;
FileWriter fw =null;
try {
fr = new FileReader("osw.txt");//默认编码不是跟随系统,是跟随编译器的编码格式
fw = new FileWriter("ocw.txt");
char[] chs = new char[1024];
int len= 0;
while((len = fr.read(chs))!=-1){
fw.write(chs, 0, len);
fw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
以上就是字符流的输入和输出的一些常用方法,高效缓冲流放在下一篇!