字符输入流(Reader)
字符流和字节流差不多,只不过字符流是由字符组成。
//因为Reader是抽象类,所以使用时要引用子类的地址
Reader reader = new FileReader("F:\\aa\\test.txt");
案例
public class FileReaderDemo {
public static void main(String[] args) {
try {
demo2();
} catch (IOException e) {
e.printStackTrace();
}
}
//一次读一个字符
public static void demo1() throws IOException {
Reader reader = new FileReader("F:\\aa\\test.txt");
int date;
while ((date = reader.read()) != -1) {
System.out.print((char) date);
}
}
//一次读多个字符
public static void demo2() throws IOException {
Reader reader = new FileReader("F:\\aa\\test.txt");
char[] chars = new char[4];
int date = reader.read(chars);
System.out.println(date);
System.out.println(new String(chars));
}
//循环读取,若是想要一次读完全部内容,可以把char[100]的值设置大一点,这样就不用循环读取
public static void demo3() throws IOException {
Reader reader = new FileReader("F:\\aa\\test1.txt");
char[] chars = new char[100];
int date;
while ((date=reader.read(chars)) != -1){
System.out.println(new String(chars));
chars = new char[100];
System.out.println(date);
}
}
}
字符输出流(Writer)
//true是追加,不会覆盖源文件
Writer writer = new FileWriter("F:\\aa\\test.txt",true);
public class FileWriteDemo {
public static void main(String[] args) {
try {
demo();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void demo() throws IOException {
Writer writer = new FileWriter("F:\\aa\\test.txt",true);//true是追加,不会覆盖源文件
writer.write("这是个神马玩意");
writer.write("今天要去干嘛");
writer.flush();//刷新缓冲区
}
}
字符流和字节流差不多,只不过一个是以字符为单位,一个是以字节为单位。要是不懂的可以看看博主上一篇字节流的文章。
字节流链接.