读取文件直到遇到“EOF”。我怎么能抓住这个?

时间:2014-02-08 08:29:21

标签: java file-io

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

data.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 

1 个答案:

答案 0 :(得分:0)

records[conter-1].str1 != "EOF"无法使用,请尝试!records[conter-1].str1.equals("EOF")