Java 8 Read File Form Class Path
In this article you lot volition acquire how to read a file from the Coffee Classpath.
We accept already explained What is a Coffee classpath? in the Java classpath commodity. In the article you lot're reading now, you will learn how to properly access files in your Classpath.
- How to setup the classpath
- How to read a file from the classpath with getClass().getResource()
- How to read a file from the classpath via ClassLoader
- Additional examples
On the image below we tin can see the architecture behind reading files from classpath in Java. Parts of the image are explained in detail in the following paragraphs.
1. How to setup the classpath
First we need to add a file to classpath. There are 2 possibilities for this:
- If the file that we want to read exists under a specific folder inside src (respectively bin or target folder), we normally do not need to do anything since the IDE does it for us by adding the files automatically to the compiled binder (usually bin or target)
- If the file that we want to exist read is in a jar file, so we demand to add jar file to our Classpath
Next (only to be sure) nosotros are going to double bank check the build directory. To practice that go hither:
ProjectName > Properties > Coffee Build Path > Source tab
At present nosotros can read resource file in Coffee.
ii. How to read a file from the classpath with getClass().getResource()
Lets say that we accept created Java projection called ClasspathExample and nosotros demand to read example.xml from information technology, firstly we need to add resources folder to classpath and and so read information technology.
package com.xenovation;import java.io.File;
import java.net.URL;public class ClasspathExample {
public File readFileFromClasspath() {
URL fileUrl = getClass().getResource("/case.xml");
return new File(fileUrl.getFile());
}
}
Here we used getClass().getResource(), this method is trying to read our fileexample.xml from the root "/" path of the classpath. In case the path does not start with "/", the file is getting searched in the same packet of the course (in our case that would be "com.xenovation").
3. How to read a file from the classpath via ClassLoader
We can also use ClassLoader instance, we can obtain it by using getClass().getClassLoader(). It goes like this:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("example.xml");
String data = readFromInputStream(input Stream);
The primary difference is that when nosotros use getResourceAsStream on a ClassLoader instance, the path is treated equally absolute starting from the root of the classpath. In any example it is recommended to always utilise absolute paths to access the file in the classpath.
iv. Additional examples
Here is an case of using getClass().getResource() and ClassLoader:
package myTestPackage;import java.io.IOException;
import java.net.URL;
import coffee.nio.file.Files;
import java.nio.file.Paths;public grade Examples {
private static final String line = "-----------------------------------------";private void loadResource (String resources) throws IOException {
URL u = this.getClass().getResource(resource);
loadResourceByUrl(u, resource);
}individual void loadResourceWithContextLoader (String resource) throws IOException {
URL u = Thread.currentThread().getContextClassLoader().getResource(resource);
loadResourceByUrl(u, resource);
}individual void loadResourceWithSystemClassLoader (String resource) throws IOException {
URL u = ClassLoader.getSystemClassLoader().getResource(resource);
loadResourceByUrl(u, resource);
}private void loadResourceByUrl (URL u, String resource) throws IOException {
Organization.out.println("-> attempting input resources: "+resource);
if (u != null) {
String path = u.getPath();
path = path.replaceFirst("^/(.:/)", "$ane");
System.out.println(" absolute resource path found :\n " + path);
String south = new String(Files.readAllBytes(Paths.get(path)));
Organization.out.println(" file content: "+s);
} else {
Organisation.out.println(" no resource found: " + resource);
}
}public static void main (String[] args) throws IOException {
Examples a = new Examples();
System.out.println(line+"\nusing this.getClass().getResource\n"+line);
a.loadResource("test-pkg-resource.txt");
a.loadResource("/exam-pkg-resources.txt");
a.loadResource("root-resource.txt");
a.loadResource("/root-resources.txt");System.out.println(line+"\n using current thread context loader\north"+line);
a.loadResourceWithContextLoader("test-pkg-resource.txt");
a.loadResourceWithContextLoader("/test-pkg-resource.txt");
a.loadResourceWithContextLoader("root-resource.txt");
a.loadResourceWithContextLoader("/root-resource.txt");Organization.out.println(line+"\n using ClassLoader.getSystemClassLoader()\n"+line);
a.loadResourceWithSystemClassLoader("examination-pkg-resources.txt");
a.loadResourceWithSystemClassLoader("/exam-pkg-resource.txt");
a.loadResourceWithSystemClassLoader("root-resource.txt");
a.loadResourceWithSystemClassLoader("/root-resource.txt");}
}
The output looks similar this:
-----------------------------------------
using this.getClass().getResource
-----------------------------------------
-> attempting input resource: test-pkg-resource.txt
absolute resource path constitute :
C:/load-resource/out/production/load-resource/com/logicbig/instance/examination-pkg-resource.txt file content: test file, local to package
-> attempting input resource: /test-pkg-resource.txt
no resource found: /test-pkg-resource.txt
-> attempting input resource: root-resource.txt
no resource establish: root-resource.txt
-> attempting input resource: /root-resource.txt
absolute resource path institute : C:/load-resource/out/product/load-resource/root-resource.txt file content: root exam file
-----------------------------------------
using current thread context loader
-----------------------------------------
-> attempting input resource: test-pkg-resource.txt
no resource found: test-pkg-resource.txt
-> attempting input resources: /examination-pkg-resource.txt
no resource establish: /test-pkg-resource.txt
-> attempting input resource: root-resource.txt
absolute resource path institute : C:/load-resource/out/product/load-resource/root-resources.txt file content: root test file
-> attempting input resource: /root-resources.txt
no resource found: /root-resource.txt
-----------------------------------------
using ClassLoader.getSystemClassLoader()
-----------------------------------------
-> attempting input resources: test-pkg-resources.txt
no resources constitute: test-pkg-resource.txt
-> attempting input resource: /test-pkg-resource.txt
no resource found: /test-pkg-resource.txt
-> attempting input resource: root-resource.txt
absolute resource path constitute : C:/load-resource/out/production/load-resource/root-resource.txt file content: root test file
-> attempting input resources: /root-resource.txt
no resource plant: /root-resources.txt
In this instance nosotros first created a line which is used later in the program. After that we told the program to search for paths using get.Class().getResource, using thread context loader and by using ClassLoader.getSystemClassLoader(). If in one of those attempts programm found a path it would impress out that the absolute resource path is found along with the path, if not it would simply say that the resource is not found.
More than to read well-nigh handling files:
How to access files in Java
Read from File in Java
Write to File in Java
fredericksonsurries.blogspot.com
Source: https://xenovation.com/blog/development/java/java-read-file-from-classpath
0 Response to "Java 8 Read File Form Class Path"
Enregistrer un commentaire