Evan Kim
Evan Kim

Reputation: 829

Incorrect Absolute File Path

I need a relative path for a csv file I have called GameDatabase.csv. It is in the same folder as my main method which are both in zzz folder.

The file kept turning up not found so I decided to print the absolute path

String db = "GameDatabase.csv";
File file = new File(db);
String path = file.getAbsolutePath();
System.out.print("\npath " + path);

The output is

path xxx\IdeaProjects\CISC_231\FinalProject\GameDatabase.csv

However the path that I am looking for is

xxx\IdeaProjects\CISC_231\FinalProject\zzz\GameDatabase.csv

Why is the absolute file path printing this out? What is going on in the background and how can I change it to get the correct file path?

Upvotes: 1

Views: 1521

Answers (2)

w4bo
w4bo

Reputation: 905

That is because, when you look for a file, the default directory is the project one (in this case FinalProject)

I structured the project as follows

enter image description here

Main.java and GameDatabase.csv are both in src

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(new File("GameDatabase.csv").exists()); // the file does not exist in FinalProject folder
        System.out.println(new File("src/GameDatabase.csv").exists()); // but exists in FinalProject/src
        System.out.println(Main.class.getClassLoader().getResourceAsStream("GameDatabase.csv").toString()); // this is a solution to look for the file within the classpath
    }
}

The output is

false
true
java.io.BufferedInputStream@7852e922

Upvotes: 5

glundin
glundin

Reputation: 31

String db = "GameDatabase.csv";
File file = new File(db)

You can create a File object representing a file that doesn't actually exist. What you have done is creating a File object representing the file "GameDatabase.csv" in the current working directory (this file does not exist) and then you printed the absolute path it would have if it existed.

Upvotes: 2

Related Questions