Altober
Altober

Reputation: 966

java.net.URL refer to a file in a parent directoty

I have a very basic question. I need a URL object but the file is in the previous directory relative to the project.

For instance, if I do

File testFile = new File("../../data/myData.xml");

works perfectly fine, it finds the file

However,

URL testURL = new URL("file:///../../data/myData.xml")

gives an

Exception in thread "main" java.io.FileNotFoundException: /../../data/myData.xml

Any idea, how to solve, work around this? without changing the position of the data?

Thanks a lot in advance Altober

Upvotes: 2

Views: 657

Answers (3)

Hitesh Kumar
Hitesh Kumar

Reputation: 653

/**
 * @param args
 */
public static void main(String[] args) {

try {
    URL testUrl = new URL("file://C:/Users/myName/Desktop/abc.txt");
    System.out.println(testUrl.toString());
} catch (MalformedURLException e) {

    e.printStackTrace();
}

    }
}

The above code is working file, just tested it, so you need to use file:// and if possible try full path

Upvotes: 1

Miserable Variable
Miserable Variable

Reputation: 28752

Exception in thread "main" java.io.FileNotFoundException: /../../data/myData.xml

Note that it is looking for parent directory of root directory, not of current directory.

I dont know if File URLs can refer to relative paths, try

‘new URL("file://../../data/myData.xml")'‘

Upvotes: 0

lakshman
lakshman

Reputation: 2741

you can use this

URL testURL = new File("../../data/myData.xml").toURI().toURL();

Upvotes: 2

Related Questions