import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReader fr = null;
//创建一个文件读取流对象,和指定名称的文件相关联
//要保证该文件是已经存在的,如果不存在就会大声fileNotFoundException异常
try {
fr = new FileReader("demo.txt");
int ch = 0;
try {
// while (true) {
// ch = fr.read();
// if(ch == -1)
// break;
// System.out.println("ch+"+(char)ch);
// }
//第一种方式 单个读
// do {
// ch = fr.read();
// System.out.println("ch+"+(char)ch);
// } while (ch!=-1);
//第二种方式 读取char[]
//该read(char[])返回值是读取到字符的个数
char [] buf = new char[3]; //一般定义1024的整数倍
int num = 0;
while ((num =fr.read(buf)) != -1 ) {
System.out.println("num"+num);
System.out.println(new String(buf,0,num));//读几个 就取几个
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fr!=null)
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// FileWriter fw = null;
// try {
// fw = new FileWriter("demo.txt");
// fw.write("aaddddgsgcxx");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// if(fw!=null)
// try {
// fw.close();
// } catch (IOException e2) {
// // TODO: handle exception
// e2.printStackTrace();
// }
// }
}
}
(3)打印 .java文件
//打印 .java文件
FileReader fr = null;
try {
fr = new FileReader("src/FileReaderDemo.java");
char [] buf = new char[1024];
int num = 0;
try {
while ((num=fr.read(buf))!=-1) {//-1是最后一个标志
System.out.println(new String(buf, 0, num));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("找不到文件");
} finally {
if (fr!=null)
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}