Reading and displaying data from a .txt file

后端 未结 10 963
北海茫月
北海茫月 2020-11-27 15:41

How do you read and display data from .txt files?

10条回答
  •  天涯浪人
    2020-11-27 15:50

    If your file is strictly text, I prefer to use the java.util.Scanner class.

    You can create a Scanner out of a file by:

    Scanner fileIn = new Scanner(new File(thePathToYourFile));
    

    Then, you can read text from the file using the methods:

    fileIn.nextLine(); // Reads one line from the file
    fileIn.next(); // Reads one word from the file
    

    And, you can check if there is any more text left with:

    fileIn.hasNext(); // Returns true if there is another word in the file
    fileIn.hasNextLine(); // Returns true if there is another line to read from the file
    

    Once you have read the text, and saved it into a String, you can print the string to the command line with:

    System.out.print(aString);
    System.out.println(aString);
    

    The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.

提交回复
热议问题