简体   繁体   中英

Unable to read file with Scanner in Java

I'm attempting to pass a File object to the Scanner constructor.

File file = new File("in.txt");
try{
   Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
   System.out.println(exp.getMessage());
}

I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line

Scanner fileReader = new Scanner(file);

always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK

If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:

java Program

or

java package1.package2.Program

and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/ .

I am running on linux and this is how you need to do it

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

public class Testing {

    public static void main(String args[]) throws IOException {
        Scanner s = null;
        try {
            //notice the path is fully qualified path
            s = new Scanner(new File("/tmp/one.txt"));
            while (s.hasNext()) {
                System.out.println(s.next());
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}

here is the result : 在此处输入图片说明

source from Java Docs

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