PandaBearSoup
PandaBearSoup

Reputation: 699

Getting a file in class path

I am trying to access a file using the class path like so:

String path = getClass().getProtectionDomain().getCodeSource()
            .getLocation().toString();
    File test = new File(path);
    File table = new File(test, "testFile.xlsx");

I am doing this because I need to create a Jar that will read and write to this file if it is in the same folder.

I get this error:

java.io.FileNotFoundException:  "myFilepath" (The filename, directory name, or volume label syntax is incorrect)

If I copy and paste myFilepath in a file browser it brings up my file. Anyone see what I am doing wrong, or ways I can improve my methods?

Upvotes: 0

Views: 2118

Answers (2)

G.Srinivas Kishan
G.Srinivas Kishan

Reputation: 438

Instead of trying to get the class path name, Create a File object and then get its absolute path using the getAbsolutePath() method. This will give the path of the source file which runs the code.

Kindly try the below code:-

 java.io.File f = new java.io.File("H");
        String path;
        path = f.getAbsolutePath();
        path = path.substring(0, (path.length() - f.getName().length()));
        f.deleteOnExit();

where the string path will then contain your class file directory path.

Upvotes: 1

David Hofmann
David Hofmann

Reputation: 5775

You can't access a File in your classpath, but you can get a resource stream from your classpath and read the contents from it. You need to look at this answer https://stackoverflow.com/a/1464366/39998

Upvotes: 0

Related Questions