a- package demo.io;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class IODemo3 {
- /**
- * 文本读取
- */
- public static void main(String[] args) {
- File srcFile = new File("c:\\Java review", "Test7.java");
- FileReader fr = null;
- try {
- fr = new FileReader(srcFile);
- System.out.println(fr.getEncoding());// 获取编码表
- // readByChar(fr);//每次读取一个字符
- readByCharBuffer(fr);//字符缓冲区读取
- //选中代码块,按 alt + shift + m 可以将代码块抽取成方法!!! 非常实用
- } catch (Exception e) {
- throw new RuntimeException("文件读取失败");
- } finally {
- if (null != fr) {
- try {
- fr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * @param fr
- * @throws IOException
- */
- private static void readByCharBuffer(FileReader fr) throws IOException {
- char[] cbuf = new char[1024];
- int len = 0;
- while((len = fr.read(cbuf))!=-1){
- System.out.println(new String(cbuf,0,len));
- }
- }
- private static void readByChar(FileReader fr) throws IOException {
- int ch = 0;
- while ((ch = fr.read()) != -1) {
- System.out.print((char) ch);// 需要将整形转为字符类型
- }
- }
- }
复制代码
|
|