Read line with Scanner

前端 未结 5 1407
野性不改
野性不改 2020-12-03 04:35

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 cod

相关标签:
5条回答
  • 2020-12-03 05:01

    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.

    0 讨论(0)
  • 2020-12-03 05:01

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

    while(r.hasNext()) {
            scan = r.next();
    
    0 讨论(0)
  • 2020-12-03 05:15
    /*
     * 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(); 
    
        }
    }
    
    0 讨论(0)
  • 2020-12-03 05:23

    This code reads the file line by line.

    public static void readFileByLine(String fileName) {
      try {
       File file = new File(fileName);
       Scanner scanner = new Scanner(file);
       while (scanner.hasNext()) {
        System.out.println(scanner.next());
       }
       scanner.close();
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      } 
     }
    

    You can also set a delimiter as a line separator and then perform the same.

     scanner.useDelimiter(System.getProperty("line.separator"));
    

    You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place

    UPDATED ANSWER for your comment:

    I just tried to create an input file with the content as below

    a
    à
    abaissa
    abaissable
    abaissables
    abaissai
    abaissaient
    abaissais
    abaissait
    

    tried to read it with the below code.it just worked fine.

     File file = new File("/home/keerthivasan/Desktop/input.txt");
         Scanner scr = null;
             try {
                scr = new Scanner(file);
                while(scr.hasNext()){
                    System.out.println("line : "+scr.next());
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
            }
    

    Output:

    line : a
    line : à
    line : abaissa
    line : abaissable
    line : abaissables
    line : abaissai
    line : abaissaient
    line : abaissais
    line : abaissait
    

    so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably

     scr = new Scanner(file);
     scr.useDelimiter("\r\n");
    

    and then do your looping to read lines. Hope this helps!

    0 讨论(0)
  • 2020-12-03 05:23

    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.

    0 讨论(0)
提交回复
热议问题