[IO流]FileReader读入数据的基本操作

12 篇文章 0 订阅
/*
 一、 流的分类:
 1. 操作数据单位:字节流、字符流
 2. 数据的流向:输入流、输出流
 3. 流的角色:节点流、处理流

 二、 流的体系结构
 抽象基类            节点流(或文件流)           缓冲流(处理流的一种)
 InputStream       FileInputStream          BufferedInputStream
 OutputStream      FileOutputStream         BufferedOutputStream
 Reader            FileReader               BufferedReader
 Writer            FileWriter               BufferedWriter

 */
public class FileReaderWriterTest {

    public static void main(String[] args) {
        File file = new File("he.txt");//相较于当前工程
        System.out.println(file.getAbsolutePath());

        File file1 = new File("chapter10\\he.txt");
        System.out.println(file1.getAbsolutePath());
    }

    /*
    将chapter10下的he.txt文件内容读入程序中,并输出到控制台

    说明点:
    1. read()的理解:返回读入的一个字符,如果达到文件末尾,返回-1
    2. 异常的处理:为了保证流资源一定可以执行关闭操作 需要使用try-catch-finally处理
    3. 读入的文件一定要存在,否则就会报FileNotFoundException
     */
    @Test
    public void testFileReader(){
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("he.txt");//相较于当前module
            //2.提供具体的流
            fr = new FileReader(file);

            //3.数据的读入
            //read():返回读入的一个字符。如果达到文件末尾,返回-1
            //方式一:
//        int data = fr.read();
//        while (data != -1){
//            System.out.print((char) data);
//            data = fr.read();
//        }

            //方式二:
            int data;
            while ((data = fr.read()) != -1){
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的关闭操作
//            try {
//                if (fr != null)
//                fr.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

            //或
            if (fr != null){
                try{
                    fr.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值