Relative to absolute path in java

2019-09-03 04:07发布

问题:

I have have a file that I want to use in my project which is in the resources package

src.res

Following what was stated in this answer, I believe that my code is valid.

File fil = new File("/res/t2.nii");
// Prints C:\\res\\t2.nii
System.out.println(fil.getAbsolutePath());  

The problem is that I that file is in my projects file not there, so I get an Exception.

How am I suppose to properly convert from relative path to absolute?

回答1:

Since you are using a Java package, you must to use a class loader if you want to load a resource. e.g.:

URL url = ClassLoader.getSystemResource("res/t2.nii");
if (url != null) {
    File file = new File(url.toURI());
    System.out.println(file.getAbsolutePath());
}

You can notice that ClassLoader.getSystemResource("res/t2.nii") returns URL object for reading the resource, or null if the resource could not be found. The next line convertes the given URL into an abstract pathname.

See more in Preferred way of loading resources in Java.



回答2:

Try with directory first that will provide you absolute path of directory then use file.exists() method to check for file existence.

File fil = new File("res");  // no forward slash in the beginning

System.out.println(fil.getAbsolutePath());  // Absolute path of res folder

Find more variants of File Path & Operations


Must read Oracle Java Tutorial on What Is a Path? (And Other File System Facts)

A path is either relative or absolute.

An absolute path always contains the root element and the complete directory list required to locate the file.

For example, /res/images is an absolute path.


A relative path needs to be combined with another path in order to access a file.

For example, res/images is a relative path. Without more information, a program cannot reliably locate the res/images directory in the file system.



回答3:

validate with

if (fil.exists()) { }

before and check if it really exist. if not then you can get the current path with

System.getProperty("user.dir"));

to validate that you are starting fromt he proper path.

if you really want to access the path you shouldnt use absolut pathes / since it will as explained start from the root of your Harddisk.

you can get the absolut path of the res folder by using this what my poster was writte in the previous answer:

File fil = new File("res");  
System.out.println(fil.getAbsolutePath());