字符流
字符输入流Reader
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Demo04 { public static void main(String[] args) throws IOException { method1(); method2(); method3(); copy(); } FileReader类
//文本文件建议用字符流读取 public static void method1() throws IOException{ //创建字符输入流 FileReader fr=new FileReader("E:\\java\\demo.txt"); int len=0; while((len=fr.read())!=-1){ System.out.println((char)len); } fr.close(); } public static void method2() throws IOException{ FileReader fr=new FileReader("E:\\java\\demo.txt"); char[] ch=new char[2]; int len=0; while((len=fr.read(ch))!=-1){ System.out.println(new String(ch,0,len));//解码 } fr.close(); } 字符输出流Writer
FileWriter类
构造方法
//往文件里写 public static void method3() throws IOException{ FileWriter fw=new FileWriter("E:\\java\\demo.txt",true); fw.write(100); fw.flush();//刷一下 char[] ch={'a','中'}; fw.write(ch); fw.flush(); fw.write("你好,小猪佩奇"); fw.close(); } flush()和close()的区别?
复制文本文件 //复制文本文件 public static void copy() throws IOException{ //明确数据源 FileReader fr=new FileReader("E:\\java\\demo.txt"); //明确目的文件 FileWriter fw=new FileWriter("E:\\java\\c.txt"); int len=0; char[] ch=new char[2]; while((len=fr.read(ch))!=-1){ fw.write(ch, 0, len); fw.flush(); } fr.close(); fw.close(); } }