How to Get Absolute Path to File in /Resources Folder of Your Project

How to get absolute path to file in /resources folder of your project

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

OR

Although this may not work all the time, a simpler solution -

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();

How to get the absolute path for the resources directory in Java?

There could be a long philosophical discussion about the pro´s and con´s, if one should "have this question". But if you bump into it too like me, than this could be a way to go, if you want to do it with a current Java style (assumption: you´re file_in_resources.txt resides inside the appropriate and Unittest standard folder src/test/resources):

private String readFileFromResourcesAsString(String fileName) throws IOException {
Path filePath = Paths.get("./src/test/resources/yourCustomPathHere/" + fileName);
return Files.lines(filePath).collect(Collectors.joining());
}

If you really want to stick to the folder view/api/target/classes/, you could use that Paths.get-statement with a java.net.URI instead (like Chetan Jadhav CD already mentioned):

Paths.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());

This solution makes use of the more recent Java-APIs around NIO.2 (see oracle tutorials here) like

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

and some Java 8 stream API part to read the Files content into a String (you could change this part as you like :) ).

The

Paths.get(".")

is key here - it gives you the current working directory transparently whatever OS (Windows, Linux, MacOS) you´re using.

If you´re a Spring-User, the whole thing is even more easy! See so answer here.

How to get the path of src/test/resources directory in JUnit?

Try working with the ClassLoader class:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

A ClassLoader is responsible for loading in classes. Every class has a reference to a ClassLoader. This code returns a File from the resource directory. Calling getAbsolutePath() on it returns its absolute Path.

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

Java path to file in src/main/resources

The problem was that I have not included the resource in the maven build in pom file. When I included the following it worked with abcManager.class.getResource("/abc.access")

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>abc.access</include>
</includes>
</resource>
</resources>
</build>

How do I load a file from resource folder?

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
// Process line
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
.getClassLoader().getResource("sql/script.sql");

How to retrieve the absolute path of a file stored inside the jar

ClassLoader().getResource only can find resource which are contained in the classpath. This not the case for the current location of your hwc.bat.

Since you are using a Maven project, the correct location to place the file is in src/main/resources in order to find it via ClassLoader.getResource("hwc.bat").



Related Topics



Leave a reply



Submit