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();
}
}