public class 字符输出流 {
public static void main(String[] args) throws IOException {
//1、创建一个字符输出流
Writer fw = new FileWriter("b.txt");
//2、通过字符流向文件写入内容
fw.write("一定要坚强,加油,奥里给!!!",0,12);
//3、关闭流
fw.close();
}
}
运行结果
三、字符输入流代码演示
将b.txt中的内容输出到内存中
public class 字符输入流 {
public static void main(String[] args) throws Exception {
//创建一个字符输入流
Reader fr = new FileReader("b.txt");
//循环读取内容
char[] chars = new char[1024];
int len=0;
while ((len=fr.read(chars))!=-1){
//打印内容
System.out.println(new String(chars,0,len));
}
fr.close();
}
}
运行结果
四、字符流文件复制功能代码演示
将a.txt文件中的内容复制到b.txt中
//使用字符流复制文件
public class 文件复制 {
public static void main(String[] args) throws Exception {
//1、创建一个字符输入流
Reader fr = new FileReader("a.txt");
//2、创建一个字符输出流
FileWriter fw = new FileWriter("b.txt");
char[] chars = new char[1024];
int len=0;
while ((len=fr.read(chars))!=-1){
fw.write(chars,0,len);
}
//3、关闭流
fw.close();
fr.close();
}
}
一、什么是字符流字符流用于处理用ASCII字符集或Unicode(包含ASCII的国际字符集)表示的文本,可以用字符流来处理的文件有纯文本文件,HTML文档,和java源代码文件。用于读写这些流的类都是Reader和Writer的子类,对于所有的文本输入,都应使用字符流来处理,而不能直接使用字节流来处理二、字符输出流代码演示使用字符输出流向b.txt中写入内容public class 字符输出流 { public static void main(String[] args) thr