onsdag den 10. december 2014

Debugging path location in Java aka FileNotFoundExceptions

Occasionally I need to write some code which locates stuff on disk using relative paths. And sometime I get the paths wrong :/

It often turns out that the current directory of the application is slightly different than I expect. However, it is not straightforward at first how one determines the current directory of the application.

I have found the following code snippet useful to solve the problem.


1
2
3
4
5
6
import java.nio.file.Path;
import java.nio.file.Paths

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

It uses NIO so it requires Java 7+.

I got the snippet from this SO.

Ingen kommentarer:

Send en kommentar

Bemærk! Kun medlemmer af denne blog kan sende kommentarer.