简体   繁体   中英

java trouble reading line from file

My code is not reading the line from file. But I'm not sure why. Beginner level Java, any input is helpful.

Thanks.

public class ReverseWords {

public static void main(String [] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter File Name: ");
    String fileName = in.nextLine();
    File f = new File(fileName);
    try {
        Scanner input = new Scanner(f);
                    int n = input.nextInt();  
        String line = input.nextLine();
            System.out.println(line);
            String [] words = line.split(" ");

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

            }


             } catch (FileNotFoundException e) {
        e.printStackTrace();
     }

}    

With no file contents I can only make a guess.

nextInt() doesn't change the line counter in Scanner , so nextLine() call will return the rest of the line you're currently at. That's probably not what you want and it's the reason why no lines are read.

To avoid that you could explicitly change line counter by doing an extra nextLine() call after your nextInt() :

int n = input.nextInt(); 
input.nextLine();
String line = input.nextLine();

From Scanner.nextLine API doc:

This method returns the rest of the current line, excluding any line separator at the end.

I assume you got filenotfound exception.

you have to specify absolute path as input.

drive:/sample/input.txt

first try reading a source file from directly

 Scanner sc = new Scanner(new File("drive:/dir/file"));

or you can place the file where your project exists. [The folder is named as the project name] In this case you can simply specify "file.extesion" as input to read from that file.

But if the file exists: (can check with new File(filename.ext).exists()) then check whether there is input to read

for reading entire file or further lines you should put that in loop (you actually read only one line)

while(sc.hasnextLine())
{
 line=sc.nextLine()    //check it first and then process
 //process this line for words 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM