zoukankan      html  css  js  c++  java
  • 103.Java中IO流_字符流_Reader

    Reader

    方法:

    1,int read():

    读取一个字符。返回的是读到的那个字符。如果读到流的末尾,返回-1.

    2,int read(char[]):

    将读到的字符存入指定的数组中,返回的是读到的字符个数,也就是往数组里装的元素的个数。如果读到流的末尾,返回-1.

    3,close()

    读取字符其实用的是window系统的功能,就希望使用完毕后,进行资源的释放

    由于Reader也是抽象类,所以想要使用字符输入流需要使用Reader的实现类。查看API文档。找到了FileReader。

    1,用于读取文本文件的流对象。

    2,用于关联文本文件。

    构造函数:在读取流对象初始化的时候,必须要指定一个被读取的文件。

    如果该文件不存在会发生FileNotFoundException.

    public class IoTest1_Reader {
    
        public static void main(String[] args) throws Exception {
            String path = "c:/a.txt";
            // readFileByInputStream(path);
            readFileByReader(path);
        }
    
        /**
         * 使用字节流读取文件内容
         * 
         * @param path
         */
        public static void readFileByInputStream(String path) throws Exception {
            InputStream in = new FileInputStream(path);
    
            int len = 0;
            while ((len = in.read()) != -1) {
                System.out.print((char) len);
            }
    
            in.close();
        }
    
        /**
         * 使用字符流读取文件内容
         */
        public static void readFileByReader(String path) throws Exception {
            Reader reader = new FileReader(path);
            int len = 0;
            while ((len = reader.read()) != -1) {
                System.out.print((char) len);
            }
    
            reader.close();
        }
    
    }
    author@nohert
  • 相关阅读:
    04-JQuery
    03-JavaScript
    02-CSS&JS
    01-HTML
    [LeetCode]Insert Interval
    [shell编程]正则表达式
    [LeetCode]Jump Game II
    [LeetCode]Jump Game
    [LeetCode]Wildcard Matching
    [shell编程]初识sed和gawk
  • 原文地址:https://www.cnblogs.com/gzgBlog/p/13624612.html
Copyright © 2011-2022 走看看