Java进阶之旅第十一天
IO流
字符输入流
FileReader
-
创建字符输入流对象
-
构造方法 说明 public FileReader(File file) 创建字符输入流关联本地文件 public FileReader(String pathname) 创建字符输入流关联本地文件
-
-
读取数据
-
成员方法 说明 public int read() 读取数据,读到末尾返回-1 public int read(char[] buffer) 读取多个数据,读到末尾返回-1 - 细节:
- 1.按字节进行读取,遇到中文,一次读多个字节,读取后解码,返回一个整数
- 2.读到文件末尾,方法返回-1
- 细节:
-
-
代码
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("src\\a.txt");
char[] chars = new char[3];
int len;
while((len = fr.read(chars))!=-1){
System.out.print(new String(chars,0,len));
}
fr.close();
}
字符输出流
-
构造方法
-
构造方法 说明 public FileWriter(File file) 创建字符输出流关联本地文件 public FileWriter(String pathname) 创建字符输出流关联本地文件 public FileWriter(File file,boolean append) 创建字符输出流关联本地文件,续写 public FileWriter(String pathname,boolean append) 创建字符输出流关联本地文件,续写
-
-
写入数据
-
方法 说明 void write(int c) 写出一个字符 void write(String str) 写出一个字符串 void write(String str,int off,int len) 写出一个字符串的一部分 void write(char[] cbuf) 写出一个字符数组 void write(char[] cbuf,int off,int len) 写出一个字符数组的一部分
-
-
代码
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("src\\a.txt",true);
char[] chars = new char[3];
chars[0] = '你';
chars[1] = '好';
chars[2] = '啊';
fw.write(chars);
fw.close();
}