【问题标题】:Difference in reading file when using a string variable [duplicate]使用字符串变量时读取文件的差异[重复]
【发布时间】:2017-04-10 13:16:40
【问题描述】:

我已经编写了以下代码来读取文件:

package com.test.application;

import java.io.*;
import java.io.IOException;

public class FileRead {

    public static void main(String[] args) {
        try{
            File file=new File("Hello.txt");
            FileReader fileReader=new FileReader(file);

            BufferedReader reader=new BufferedReader(fileReader);

            /*String line=null;
            while((line = reader.readLine())!=null){
                System.out.println(line);
            }   */

            System.out.println("This is using no string variable!!!");
            while(reader.readLine()!=null){
                System.out.println(reader.readLine());
            }   
            reader.close();
        }       
        catch(IOException e){

        }

    }

}

我的文本文件是:

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting  
industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the     
1500s, when an unknown printer took a galley of type and scrambled it    
to make a type specimen book. 
It has survived not only five centuries, but also the leap into 
electronic typesetting, remaining essentially unchanged. 
It was popularised in the 1960s with the release of Letraset sheets 
containing Lorem Ipsum passages, and more recently with desktop 
publishing software like Aldus PageMaker including versions of Lorem 
Ipsum.

我的问题是当我使用字符串变量从文件中读取时,我会获取文件的所有内容,即:

String line=null;
while((line = reader.readLine())!=null){
    System.out.println(line);
}   

但是,当我使用下面的代码 sn-p 读取文件时,跳过了几行,并且没有读取整个文件。

while(reader.readLine()!=null){
    System.out.println(reader.readLine());
}   

谁能解释一下为什么会这样。

【问题讨论】:

    标签: java java-io


    【解决方案1】:

    这可能会发生,因为在您的non-string variable 案例中,您调用readLine() 两次,并且只打印第二项。每个readLine() 调用从文件中读取行并将当前位置指针移动到下一行。 我建议你使用一个中间字符串变量。

    【讨论】:

    • 谢谢,就是这样,我应该注意到了。
    【解决方案2】:

    在您的第二次剪断中,您两次调用reader.readLine()。每次调用都会“消耗”一行,因此您只需要每隔一行打印一次。

    【讨论】:

      【解决方案3】:

      您调用 .readLine() 两次,第一次在 while 中,第二次在 println 中,只有第二次会输出。

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 1970-01-01
        • 2011-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多