Tags down


How to read text file using scanner

By : Pooriya
Date : July 31 2020, 07:00 AM
wish of those help Im trying to read text from a file and compare it to user input. But when I run it I can get an error that reads. I don't know what's wrong any help will be appreciated! , You are closing it:
code :
   if(userName.equals(uName) && passWord.equals(pWord)) 
          System.out.println("Welcome " + userName + "!");
          System.out.println("Menu: ");
          System.out.println("\t1) Account");
          System.out.println("\t2) Payroll");
          System.out.println("\t3) Attendance Report");
          System.out.println("\t4) Service Desk");
          int answer = sc.nextInt(); //here

           switch (answer)  {

              case 1:
                  System.out.print("Welcome to Account!");
              case 2:
                  System.out.print("Welcome to Payroll!");
              case 3:
                  System.out.print("Welcome to Attendance Report!");
              case 4:
                  System.out.print("Welcome to Service Desk!");
                  System.out.print("Enter correct menu option");

          System.out.println("Sorry, you entered invalid credentials. Try again. ");

Share : facebook icon twitter icon

Scanner unable to read text file

By : Nick Balak
Date : March 29 2020, 07:55 AM
will be helpful for those in need The Scanner type is weirdly inconsistent when it comes to handling input. It swallows I/O exceptions - consumers should test for these explicitly - so it is lax in informing readers of errors. But the type is strict when decoding character data - incorrectly encoded text or use of the wrong encoding will cause an IOException to be raised, which the type promptly swallows.
This code reads all lines in a text file with error checking:
code :
  public static List<String> readAllLines(File file, Charset encoding)
      throws IOException {
    List<String> lines = new ArrayList<>();
    try (Scanner scanner = new Scanner(file, encoding.name())) {
      while (scanner.hasNextLine()) {
      if (scanner.ioException() != null) {
        throw scanner.ioException();
    return lines;
  public static List<String> readAllLinesSloppy(File file, Charset encoding)
      throws IOException {
    List<String> lines = new ArrayList<>();
    try (InputStream in = new FileInputStream(file);
        Reader reader = new InputStreamReader(in, encoding);
        Scanner scanner = new Scanner(reader)) {
      while (scanner.hasNextLine()) {
      if (scanner.ioException() != null) {
        throw scanner.ioException();
    return lines;

Getting scanner to read text file

By : Peter Marczis
Date : March 29 2020, 07:55 AM
it fixes the issue I am trying to use a scanner to read a text file pulled with JFileChooser. The wordCount is working correctly, so I know it is reading. However, I cannot get it to search for instances of the user inputted word. , You'll have to look for
, ; . ! ? etc.
code :
//this will remove a certain character with a blank space
word = word.replaceAll(".","");
word = word.replaceAll(",","");
word = word.replaceAll("!","");
//NOTE:  This example will not work for you.  It's just a simple example for seeing a Regex.
//Removes whitespace between a word character and . or ,
String pattern = "(\\w)(\\s+)([\\.,])";
word = word.replaceAll(pattern, "$1$3"); 

Using Scanner to read from text file

By : user3459825
Date : March 29 2020, 07:55 AM
hope this fix your issue You fire nextLine more than once. You should store nextLine() in a variable at the start of your while() structure and use that.
If you are, by example, at line 10 you will try to read line 10 and line 11.

How To Read A Text File Via Scanner

By : UserXYZ
Date : March 29 2020, 07:55 AM
seems to work fine I guess your problem is that you are trying to read a file that you are currently using, try close the fout object before read it, something like this:
code :
public static void main(String[] args){
    File file = new File("ToDoItems.txt");
    ToDoItem td = new ToDoItem();
    ToDoList tl = new ToDoList();

    Scanner keyboard = new Scanner(System.in);

    ArrayList<String> list = new ArrayList<>();
    String inputline;

    System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
    try (PrintWriter fout = new PrintWriter(file)) {
    //                                       ^^ here
        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                fout.print(td.getDescription() + System.lineSeparator());
            } else {
                // Important line is here!
                fout.close(); // <--- Close printwriter before read file

                System.out.println("Here is the list so far:");
                Scanner ReadFile = new Scanner(file);

                while (ReadFile.hasNext()) {
                    String listString = ReadFile.nextLine();
        } while ("y".equals(inputline));
    } catch (FileNotFoundException e) {

Using Scanner to read in a text file

By : G. Cosnett
Date : March 29 2020, 07:55 AM
I hope this helps you . I honestly have no idea what you're trying to do here. You'd better scan it once:
code :
    File comms = new File("src/Resources/com.txt");
    try(Scanner scan = new Scanner(comms)) {
        while(scan.hasNext()) {
            String line = scan.nextLine();

            String[] words = line.split(" ");

            System.out.println(words[0]); // "Hi"
            System.out.println(words[1]); // "0x01"
    catch(Exception e) {

Related Posts Related Posts :
  • Java EE 7 batch API (JSR-352): it's possible to stop a single step and not all the job?
  • Java multithread example - is object shared or not
  • Why String's replaceAll() method come at high performance cost at the first time and faster at the next time?
  • Lua script coverts empty array to object
  • Doesn't Access to external storage in API-29
  • How to add a button to the Android system navigation bar?
  • If inside for-each-loop to Stream
  • Shift array to the right by one slot
  • How to setup a Java development environment for Z3
  • how to make notify() works properly with wait()
  • IllegalFormatConversionException d != java.lang.Integer when trying to printf date?
  • Duplicate logic in backend and frontend with Domain Driven Design
  • How would I randomize an int[][]?
  • StringDate to Date coming in different Time in SimpleDateFormat in java
  • Get content uri from file path in android for video
  • function param issue in Scala 11, works in Scala 12 using resilience4j
  • Android unit testing : calling a method from fragment which uses context
  • How to remove E notation from Double value
  • Check if input is any of the values in an array
  • DateTimeParseException - could not be parsed at index 0
  • How to make a Java HTTP async request?
  • Make Javafx/Scenebuilder recognize tagged fields and methods when splitting the MainController into multiple files?
  • Why does this time fail to be parsed by DateTimeFormatter.ofPattern()?
  • Java - Merge objects of list given a condition
  • How to know if arraylist contains value in property of object?
  • Java modelling class if objects have same properties but they are fundamentally different
  • False Positive and False Negative
  • Java UnknownFormatConversionException = ','
  • Apache POI recording only 1 row in the spreadsheet
  • Getting Constructor from Java Class that would be called for argument types, not requiring exact argument & paramete
  • @JsonIgnore with Conditions
  • Does synchronizing on the static field that you are modifying make your code thread safe?
  • Compiler errors while trying to make a pop up
  • Trying to take two timestamps, subtract them, convert the difference to seconds and store in an int variable
  • How can I use Optionals instead of nested if statement?
  • How do I compare values in parallel arrays to eliminate duplicates?
  • make a method which returns the number of one digit numbers in an array
  • Does calling multiple times save() method of hibernate with same object insert new record in DB?
  • Single Number solving by Haspmap, return always be a "@"
  • What do you do about the JLabel classes? It says, "JLabel not a statement" for the error
  • Functional Interface call for a new Instance
  • When I tried to add ArrayList into ArrayList second ArrayList is repeating
  • How can I print the longest word from a user defined list?
  • enabling authentication in ignite
  • Providing OSGi Service Without Implementing Interface
  • Read manifest from JAR with gradle
  • Create one element Set the same way (if applicable) as create single element list
  • pass by reference an integer in java
  • how to generate the POI excel file in a specific location?
  • Issue trying to create a Bubble Sort using ArrayList<Integer>
  • How can I avoid typechecking in this situation
  • How to create a map<k,v> between first and last nested object using Java streams?
  • First time writing junit: Need suggestions
  • what is the best solution to split in chunk monthly given two dates startTime and EndTime in Java?
  • View Binding causes "The specified child already has a parent"
  • parse float in java with trailing junk
  • How to convert color from ColorPicker to String value in javaFX
  • Spring test integration not run how I deal with this error?
  • Java 8 Streams : Count the occurrence of elements(List<String> list1) from list of text data(List<String> li
  • What is the difference between static and protected in java?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org