• Java获取文件内容IO流


    一般读取文件类的使用字符流即可

    InputStream和Reader

    InputStream和Reader是Java IO中的两个重要的抽象基类,InputStream是二进制流,Reader是字符流。使用InputStream或者Reader读取文件内容可以帮助我们读取文本文件(非二进制文件)的内容。

    下面是一个使用Reader读取文件内容的示例代码:

    
    File file = new File("test.txt");
    try {
        FileReader reader = new FileReader(file);
        BufferedReader br = new BufferedReader(reader);
        String str;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
        br.close();
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    使用FileReader类读取文件内容,并将FileReader对象传入BufferedReader类中以便于一次读取一行,然后逐行读取并输出文件内容。

    Scanner

    Scanner是Java内置的一个读取用户输入的类,他也可以用于读取文件内容。使用Scanner读取文件内容需要先创建File对象,并将其传入Scanner构造函数中。

    下面是一个使用Scanner读取文件内容的示例代码:

    File file = new File("test.txt");
    try {
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    使用Scanner类读取文件内容,并通过while循环和hasNextLine()方法逐行读取文件内容并输出到控制台。

    NIO

    Java NIO(New IO)是从Java 1.4开始引入的一组新IO API。相较于之前的IO API,NIO提供了更高效的IO操作和更多的控制选项。下面是一个使用NIO读取文件内容的示例代码:

    File file = new File("test.txt");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        fileChannel.read(byteBuffer);
        byteBuffer.flip();
        byte[] bytes = byteBuffer.array();
        System.out.println(new String(bytes, 0, bytes.length));
        fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    使用FileInputStream读取文件内容,并调用getChannel()方法获取FileChannel对象,然后调用read()方法将文件内容读入到ByteBuffer缓冲区中。最后通过flip()方法将缓冲区设置为读模式,并通过byteBuffer.array()将缓冲区中的内容转换为字节数组,再通过new String()方法将字节数组转换为字符串并输出到控制台。

    外传

    😜 原创不易,如若本文能够帮助到您的同学
    🎉 支持我:关注我+点赞👍+收藏⭐️
    📝 留言:探讨问题,看到立马回复
    💬 格言:己所不欲勿施于人 扬帆起航、游历人生、永不言弃!🔥
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    聚观早报 | 荣耀Play8T上市;阿芙“超级品牌日”上线
    2月26日做题总结(C/C++真题)
    C#WPF数字大屏项目实战06--报警信息
    VR技术的应用与发展_华锐互动
    固体物理 2022.9.30
    【Redis】数据过期策略和数据淘汰策略
    前端bootstrap+fileInput+django后端文件编辑回显
    Shiro-官方文档及使用
    oracle报错 ORA-02290: 违反检查约束条件问题
    python中如何实现多进程,用进程的优缺点有啥?
  • 原文地址:https://blog.csdn.net/fclwd/article/details/132628694