문제

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

도움이 되었습니까?

해결책

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 : enter image description here

source from Java Docs

다른 팁

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/.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top