Read line with Scanner

前端 未结 5 1423
野性不改
野性不改 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: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(); 
    
        }
    }
    

提交回复
热议问题