Search code examples
javatokenfilereader

Program only reading one line instead of entire file


    public static void main(String ar[]) throws FileNotFoundException{
    scan = new Scanner(new FileReader(new File("files.txt")));
    String nextLine = scan.nextLine();
    String[] fileNames = nextLine.split("\\s+");

    for(int i=0;i<fileNames.length;i++){
        System.out.println(fileNames[i]);
    }


    for(int i=0;i<nextLine.length();i++){
        char c = nextLine.charAt(i);
        boolean isWhiteSpace = isWhiteSpace(c);
        if(isWhiteSpace){
            if(c == ' ')
                System.out.println("white space (blank) at index "+i);
            if(c == '\n')
                System.out.println("white space (line feed) at index "+i);
            if(c == '\r')
                System.out.println("white space (\\r - carriage return) at index "+i);
            if(c == '\t')
                System.out.println("white space (\\t - tab) at index "+i);
        }
    }

} 

I need help in solving this issue. Apparently my program only recognizes the first line in the file, when it supposed to be reading the whole file for the content.

What changes do I need to make for that? thanks.


Solution

  • Well, this is because you are only reading one line from the file:

    scan = new Scanner(new FileReader(new File("files.txt")));
    String nextLine = scan.nextLine();
    

    In order to read the entire file you have to call scan.nextLine() until you reach the end of file. To check for end of file you can do a while loop and thus go through the whole file:

    Scanner input = new Scanner(new File("\""+filename+"\""));
    while(input.hasNextLine())
    {
        String data = input.nextLine();
        //Do what you want with one line which is at each iteration stored in data
    }