如何仅使用FileReader读取多行? [英] How to read multiple lines using FileReader only?

查看:172
本文介绍了如何仅使用FileReader读取多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class Reader {
    public static void main(String[] args) throws IOException {
        try (FileReader in = new FileReader("D:/test.txt")) {
            // BufferedReader br = new BufferedReader(in);
            int line = in .read();
            for (int i = 0; i < line; i++) {
                //System.out.println(line);

                System.out.println((char) line);
                line = in .read();
            }
        }
    }
}

和文件Test.txt,其内容为:

Hello
Java

当我运行上面的代码时,它只会读取Hello.我只想使用FileReader读取多行.我不想使用BufferedReaderInputStreamReader等.这可能吗?

When I run above code it only reads Hello. I would like to read multiple lines using FileReader only. I don't want to use BufferedReader or InputStreamReader etc. Is that possible?

推荐答案

在没有任何缓冲流的情况下逐字符读取文件是极其无效的.我可能会将FileReader包装在某些BufferedReader中,或者仅使用Scanner来读取文件的内容,但是如果您绝对希望/需要/只使用FileReader,则可以尝试使用

Reading file character by character without any buffering stream is extremely ineffective. I would probably wrap FileReader in some BufferedReader or simply used Scanner to read condent of file, but if you absolutely want/need/have to use only FileReader then you can try with

int line = in.read();
while (line != -1) {
    System.out.print((char) line);
    line = in.read();
}

代替您的for (int i = 0; i < line; i++) {...}循环.

仔细阅读苗条的答案.简而言之:读取条件不必在乎您读取的字符数是否小于当前读取字符的数字表示形式(i < line).就像在

Read carefully slims answer. In short: reading condition shouldn't care if number of characters you read is less then numeric representation of currently read character (i < line). Like in case of

My name

is

not important now

此文件中的字符很少,通常不会像\r\n那样显示,而实际上看起来像

This file has few characters which you normally will not see like \r and \n and in reality it looks like

My name\r\n 
\r\n 
is\r\n 
\r\n 
not important now

其中\r的数字表示形式为10,因此在阅读My name\r\n之后(由于\r\n是表示行分隔符的单个字符,所以它是9个字符),您的i将变为,并且由于您要尝试读取的下一个字符是\r(也由10表示),您的条件i<line将失败(10<10不是真的).​​

where numeric representation of \r is 10, so after you read My name\r\n (which is 9 characters because \r and \n are single character representing line separator) your i will become 10 and since next character you will try to read is \r which is also represented by 10 your condition i<line will fail (10<10 is not true).

因此,而不是检查i<line,您应该检查读取的值是否不是

So instead of checking i<line you should check if read value is not EoF (End of File, or End of Stream in out case) which is represented by -1 as specified in read method documentation so your condition should look like line != -1. And because you don't need i just use while loop here.

返回:

读取的字符,如果已到达流的末尾,则为-1

The character read, or -1 if the end of the stream has been reached

这篇关于如何仅使用FileReader读取多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆