2

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

1
  • You need to give the complete path to the file Commented Feb 20, 2014 at 15:14

3 Answers 3

2

you can use this

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

Sign up to request clarification or add additional context in comments.

Comments

1
/**
 * @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

1 Comment

thanks a lot but the idea was to try to avoid absolute paths, since it is a project shared by many developers.
0

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")'‘

2 Comments

"I dont know if File URLs can refer to relative paths" <-- no they cannot. Paths in absolute URIs (and therefore URLs) are always absolute. That is, if you do not use relative URIs.
I tried that. It seems that fge is right. Lakshman has the right answer. Thank you for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.