[java] Read line with Scanner

EDIT for further readers: the problem was that my input file was corrupted.

I don't understand what I'm doing wrong :

I was using this code :

    File f = new File("C:\\Temp\\dico.txt");
    BufferedReader r = null;
    try {
        r = new BufferedReader(new FileReader(f));
        String scan;
        while((scan=r.readLine())!=null) {
            if(scan.length()==0) {continue;}
            //treatment
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if(r!=null) try {
            r.close();
        } catch (IOException ex) {
            Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Which is working fine. Now, for some reason, I wanted to change for a Scanner. My code became :

    File f = new File("C:\\Temp\\dico.txt");
    Scanner r = null;
    try {
        r = new Scanner(f);
        String scan;
        while(r.hasNextLine()) {
            scan = r.nextLine();
            if(scan.length()==0) {continue;}
            //treatment
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if(r!=null) r.close();
    }

This time, we never enter the while, because r.hasNextLine() always returns "false". Any idea about what I'm doing wrong ?

I precise that nothing else changed, the file is still the same.

EDIT : I also precise that I tried with another file and got the same result, meaning it doesn't comes from the file apparently.

The file looks like this :

a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
...

Edit 2 : The content of the file seems to be problematic since the problem persists only if I copy/paste the content from my file to another. In clear, if I write the content myself, it works, if I use a part of the content of my dico.txt file, it doesn't work. Any explanation ?

Edit 3 : These are the links to my files. I advice you to avoid the dico.txt which is very huge.

dico.txt : https://drive.google.com/file/d/0B0sroFy9HZlBNDl3MUwzVnh6VU0/edit?usp=sharing

test.txt : https://drive.google.com/file/d/0B0sroFy9HZlBemZjbXU1RmlmdjQ/edit?usp=sharing

This question is related to java java.util.scanner readline

The answer is


next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.


Try to use r.hasNext() instead of r.hasNextLine():

while(r.hasNext()) {
        scan = r.next();


For everybody who still can't read in a simple .txt file with the Java scanner.


I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.

The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)

The Scanner shouldn't have any problem after this.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to java.util.scanner

How do I use a delimiter with Scanner.useDelimiter in Java? How to read multiple Integer values from a single line of input in Java? What's the difference between next() and nextLine() methods from Scanner class? Read line with Scanner Rock, Paper, Scissors Game Java Java using scanner enter key pressed Scanner is never closed how to insert a new line character in a string to PrintStream then use a scanner to re-read the file Exception in thread "main" java.util.NoSuchElementException Using a scanner to accept String input and storing in a String Array

Examples related to readline

Read line with Scanner Python Serial: How to use the read or readline function to read more than 1 character at a time Getting rid of \n when using .readlines() How to use readline() method in Java? Convert InputStream to BufferedReader Why do I get the "Unhandled exception type IOException"? Best method for reading newline delimited files and discarding the newlines?