简体   繁体   中英

Scanner doesn't see file Java

I don't really understand whats the problem but my scanner just can't see the file I'm passing. I tried moving file to src, still doesn't work. Here is the code:

public static void main(String[] args) {
 File file = new File("src/1.txt");
     Scanner sc = new Scanner(file);
 int n = sc.nextInt();
 int [][] graph = new int [n][n];
 for (int x =0; x<n; x++)
     for (int y=0; y<n;y++)
         graph[x][y] = sc.nextInt();

}

File is stored at C:\\Users\\evluc\\IdeaProjects\\ka1\\src\\com\\company

You can try file.getCanonicalPath() or file.getAbsolutePath() to determine what the path of the file is you're trying to read and can therefore find out what's wrong with your relative path. I assume this is just a relative path issue and has nothing to do with the actual routine you're trying to access the file. If you know were you are pointing with the File object you will also know how you have to change your relative path. That is always the first thing to check when working with relative paths.

try below code.

 File file = new File("C:\Users\evluc\IdeaProjects\ka1\src\com\company\src\1.txt");

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            int n = sc.nextInt();
            int [][] graph = new int [n][n];
            for (int x =0; x<n; x++)
              for (int y=0; y<n;y++)
                graph[x][y] = sc.nextInt();
        }
        sc.close();
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }

The input what have you provided src/1.txt it is trying to look file at the location : C:\\Users\\evluc\\IdeaProjects\\src\\1.txt .

Either give absolute path for the file or correct your path.

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