package com.itheima.d6_char_stream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
public class FileReaderDemo01 {
public static void main(String[] args) throws Exception {
//目标:每次读取一个文件
//1.创建一个字符输入流管道与源文件接通
Reader fr = new FileReader("D:\\code\\javasepromax\\file-io-app\\src\\data03.txt");
//2.读取一个字符返回,没有可读的字符了返回-1
// int code = fr.read();
// System.out.print((char)code);
// int code1 = fr.read();
// System.out.print((char)code1);
//3.使用循环读取字符
int code ;
while ((code = fr.read()) != -1){
System.out.print((char) code);
}
}
}
package com.itheima.d6_char_stream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
public class FileReaderDemo02 {
public static void main(String[] args) throws Exception {
//1.创建一个文件字符输入流与源文件接通
Reader fr = new FileReader("D:\\code\\javasepromax\\file-io-app\\src\\out04.txt");
//2.用循环,每次读取一个字符数组的数据
char[] buffer = new char[1024]; //1K字符
int len;
while ((len = fr.read(buffer)) != -1){
String rs = new String(buffer,0,len);
System.out.println(rs);
}
}
}
package com.itheima.d6_char_stream;
import java.io.FileWriter;
import java.io.Writer;
public class FileReaderDemo03 {
public static void main(String[] args) throws Exception {
//1.创建一个字符输出流管道与目标文件接通
Writer fw = new FileWriter("D:\\code\\javasepromax\\file-io-app\\src\\out08.txt",true);//覆盖管道,每次启动 都会清空文件之前的数据
// a.public void write(int c): 写一个字符出去
fw.write(98);
fw.write('a');
fw.write('徐'); //不会出问题了
fw.write("\r\n"); //换行
// b.public void write(String c) 写一个字符串出去
fw.write("abc我是中国人" );
fw.write("\r\n"); //换行
// c.public void write(char[] buffer); //写一个字符数组出去
char[] chars = "abc我是中国人".toCharArray();
fw.write(chars);
fw.write("\r\n"); //换行
// d.public void write(String c, int pos , int len):写字符串的一部分 出去
fw.write("abc我是中国人",0,5);
fw.write("\r\n"); //换行
// e.public void write(char[] buffer , int pos , int len):写字符数组的一部分出去
fw.write(chars,3,5);
fw.write("\r\n"); //换行
// fw.flush();//刷新后流可以继续使用
fw.close();//关闭包含刷新,关闭后流不能使用
}
}