【问题标题】:Reading file until "EOF" encountered. How can I catch this?读取文件直到遇到“EOF”。我怎么能抓住这个?
【发布时间】:2014-02-08 16:36:42
【问题描述】:

如果有人能指出我正确的方向,我将不胜感激。我正在使用 Scanner 类读取文本文件。在数据文件的末尾,我有一个“EOF”预告片。我希望 while 循环在遇到“EOF”时立即停止。我的想法是将“&&”语句放在while循环中,但会引发运行时错误。

数据.txt

January Feburary March
January Feburary March
January Feburary March
January Feburary March
January Feburary March
EOF EOF EOF

代码:

public class ReadFile {

    static Scanner input;
    static final int MAX_LEN = 50;
    static int counter = 0;
    static String filePath = "data.txt";
    static File file;
    static Records[] records;

    //METHOD: MAIN
    public static void main(String[] args){ 

       records = new Records[ MAX_LEN ];          

        try {
            file = new File( filePath );
            input = new Scanner( file );

            do{            
                records[counter] = new Records();
                records[counter].str1 = input.next();               
                records[counter].str2 = input.next();               
                records[counter].str3 = input.next();
                ++counter;
            }
            while(input.hasNextLine() && records[conter-1].str1 != "EOF");
            input.close();
        }
        catch ( IOException ex ){       
            System.out.println( "File access error" );  
            counter = 0;
        }//        
    }//MAIN 

【问题讨论】:

  • 只要说当行等于行尾EOF 就可以通过使用break 中断循环来停止循环。

标签: java file-io


【解决方案1】:

records[conter-1].str1 != "EOF" 不行,试试!records[conter-1].str1.equals("EOF")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 2015-06-21
    • 1970-01-01
    • 2016-12-22
    • 2018-10-15
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多