java基础(jdk1.8)
**
文件IO——字符流
**
Java操作char来实现流的输入输出,前文说过输入输出是相对Java而言的。
字符流标识每次进行IO时最小单位为1字符,也就是1char
字符流和字节流基本内容一致,区别就在于byte和char
字符输出流
Writer 接口为字符输出流顶类
子类
- FileWriter(只能写入到文本文件)
方法
write(int); //向文件写入一个字符
write(char []); //向文件中写入字符数组
write(char [],int,int); //向文件从char的int开始,共int个字符
write(String); //写入字符串
字符输入流
Reader 接口为字符输入流顶类
子类
- FileReader(只能读文本文件)
方法
read();
read(char []);
读写文件
读:
try {
Reader read = new FileReader("d:\\a.txt");
int len;
//1 char字符 = 2 byte(字节)
char [] c = new char[10];
while ((len = read.read(c)) != -1)
{
System.out.print(new String(c,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}
写:
try {
Writer writer = new FileWriter("d:\\a.txt",true);
writer.write("字符流");
//写入时需要调用flush方法进行一次刷新,如果写操作很多的话比较消耗性能,
//因此调用flush之后才会写入之前写入缓存的内容
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
复制文件:
public static void main(String[] args){
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("d:\\a.txt");
fw = new FileWriter("d:\\c.txt");
int len;
char [] chars = new char[1024];
while ((len = fr.read(chars)) != -1)
{
fw.write(chars,0,len);
fw.flush();
}
} catch (FileNotFoundException e) {
System.err.println("文件未找到或权限不够");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null)
{
try {
fw.close();
} catch (IOException e) {
System.out.println("输出流关闭异常");
}
}
if (fr != null)
{
try {
fr.close();
} catch (IOException e) {
System.out.println("输入流关闭异常");
}
}
}
}
注意:
-
字符流是专门针对文本文件,一般来说纯英文的文本也可以使用字节流,但建议使用字符流操作文本文件
-
一般使用流时,如果使用完毕要进行close操作,流进行close要进行判空,因此代码看起来比较臃肿。
下一节转化流针对中文乱码进行说明!!!
有兴趣的关注我的公众号,一起学习交流啊
上一篇 》字节流
下一篇 》转换流