字符流读取文件
查阅API文档找到了Reader
read()方法读取单个字符,返回int值?
返回的int值,是读取到的字符的ASCII码值
read()方法,每执行一次,自动的向后读取一个字符
读取到文件末尾的时候,得到-1的值
找到Reader类的子类 FileReader
FileReader(String fileName) 传递字符串文件名
read(字符数组)
返回int值
数组中存储的就是文件中的字符
int返回值,读到末尾就是-1
int返回数组中,读取到的字符的有效个数
好处:可以提高读取的效率
注意问题:
出现异常:XXXX拒绝访问
A.操作,确认是不是操作的文件
B.登录windows的账户是不是管理员,不是管理员登录的,不能操作c盘下的文件
其他盘符是可以的
例程:字符流读取文件
import java.io.*;
//Reader是字符流读的抽象基类(输入流,读取文件的抽象基类)
public class FileReaderDemo {
public static void main(String[] args) {
FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader("F:\\f.txt");
int len = 0;// read方法返回读取的单个字符的ASCII码(可以转换成字符输出)
while ((len = fr1.read()) != -1) {
System.out.print((char) len);
}
System.out.println("\n******将字符读入缓冲数组再输出*****");
// 定义字符数组
char[] buf = new char[512];// 将512*2字节字符读入缓冲数组
fr2 = new FileReader("F:\\Thinking.txt");
while ((len = fr2.read(buf)) != -1) {//返回值len表示读取的有效字符的长度
System.out.print(new String(buf,0,len));//将字符数组包装成String
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr1 != null) {
fr1.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException("文件关闭失败");
}
try {
if (fr2 != null) {
fr2.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
例程:自己实现的一行一行读取的方法
import java.io.*;
class MyReadLine {
// 自己实现一行一行读取
private Reader r;
public MyReadLine(Reader r) {
this.r = r;
}
public String myReaderLine() throws IOException {
// 定义一个字符缓冲区,读一个字符就存储到这里
StringBuilder sb = new StringBuilder();
int len = 0;
while ((len = r.read()) != -1) {
if (len == '\r') {
continue;
}
if (len == '\n') {
return sb.toString();
} else {
sb.append((char) len);// 读到的是有效字符,存到缓冲区
}
}
//看看缓冲区是否还有内容,有可能内容不是以回车符结尾的
if (sb.length() != 0) {
return sb.toString();
} else
return null;
}
public void MyClose() {
try {
if (r != null)
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TestMyReadLine {
public static void main(String[] args) throws IOException {
MyReadLine my = null;
try {
my = new MyReadLine(new FileReader("F:\\Thinking.txt"));
String line = null;
while ((line = my.myReaderLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (my != null) {
my.MyClose();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
5.字符流的输出流(写文件)使用
字符流写文件
查阅API文档,找到了使用的子类,FileWriter
FileWriter(String fileName)
根据给定的文件名构造一个 FileWriter 对象。
void write(String str) 是FileWriter类的父类的方法
记住:Java中字符流写数据,不会直接写到目的文件中,写到内存中
想将数据写到目的文件中,刷新,刷到目的文本中
flush()刷新
记住:流对象中的功能,调用了Windows系统中的功能来完成
释放掉操作系统中的资源,简称:关闭流
close方法,关闭流之前,关闭的时候,先要刷新流中的数据
但是,如果写文件的数据量很大,写一句刷一句才好
看到了父类中的write方法
记住:IO操作,需要关闭资源,关闭资源的时候,开了几个流,就要关闭几个流
单独的进行关闭资源,单独写try catch,保证每一个流都会被关闭
例程:Writer类的使用
import java.io.*;
//Writer是字符流写的抽象基类(输出流,写入文件的抽象基类)
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter fw1 = null;
FileWriter fw2 = null;// 关流的时候要分别处理异常
try {