逐行读取指令 java

Read an instruction line by line java

我在文本文件中有一组说明:

LoadA 0

LoadB 1

Add

Store 0

LoadA 2

etc...

我知道我可以使用 Scanner 和 hasNextLine,但不确定如何实现它以及如何阅读和理解说明。

Scanner inFile = null;
try 
    {
       // Create a scanner to read the file, file name is parameter
        inFile = new Scanner (new File("whatever.txt"));
        } 
        catch (FileNotFoundException e) 
        {
        System.out.println ("File not found!");
        // Stop program if no file found
        System.exit (0);
        }

那么,

while(inFile.hasNextLine()){
    (some variable) = inFile.nextLine();
    (do something to that variable);
}

如果这不能解决问题,我建议您看一下 http://www.cs.swarthmore.edu/~newhall/unixhelp/Java_files.html

尽管上面的人希望你自己做这个我会回答这个问题因为我记得学习是多么困难。只要你从中学习而不只是复制它们,这应该会有用。

Scanner sc = new Scanner(System.in);   //read from the System.in
while (sc.hasNextLine()) { //this will continue to itterate until it runs out
     String[] x = sc.nextLine().split(" ");
     //this takes your input and puts it into a string array where there is a 
     //space e.g. ["LoadA", "0"]
}

希望对您有所帮助。您仍然需要解决问题。您现在可以立即获取内容。祝你好运。