Read a File From a Url Java

In this article you lot will acquire how to read a file from the Java Classpath.

We have already explained What is a Java classpath? in the Coffee classpath article. In the article you're reading now, you will learn how to properly access files in your Classpath.

  1. How to setup the classpath
  2. How to read a file from the classpath with getClass().getResource()
  3. How to read a file from the classpath via ClassLoader
  4. Additional examples

On the image below nosotros tin can run across the architecture behind reading files from classpath in Java. Parts of the image are explained in detail in the following paragraphs.

read files from classpath architecture
diagram how files in classpaths are accessed

1. How to setup the classpath

First we need to add a file to classpath. There are 2 possibilities for this:

  1. If the file that we desire to read exists under a specific folder inside src (respectively bin or target folder), we usually practise not demand to do anything since the IDE does it for usa past adding the files automatically to the compiled folder (usually bin or target)
  2. If the file that nosotros want to be read is in a jar file, and so we demand to add jar file to our Classpath

Adjacent (merely to exist certain) we are going to double check the build directory. To do that go here:

ProjectName > Properties > Coffee Build Path > Source tab

Now we tin can read resource file in Java.

2. How to read a file from the classpath with getClass().getResource()

Lets say that we have created Java projection called ClasspathExample and we need to read example.xml from information technology, firstly we need to add resource binder to classpath and then read it.

package com.xenovation;

import java.io.File;
import coffee.internet.URL;

public form ClasspathExample {

public File readFileFromClasspath() {
URL fileUrl = getClass().getResource("/example.xml");
render 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 instance the path does non kickoff with "/", the file is getting searched in the same bundle of the class (in our example that would exist "com.xenovation").

3. How to read a file from the classpath via ClassLoader

Nosotros can also use ClassLoader instance, we tin obtain it past using getClass().getClassLoader(). It goes like this:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("instance.xml");
String data = readFromInputStream(input Stream);

The main divergence is that when nosotros apply getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath. In any instance it is recommended to always employ absolute paths to admission the file in the classpath.

4. Additional examples

Here is an example of using getClass().getResource() and ClassLoader:

package myTestPackage;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import coffee.nio.file.Paths;

public class Examples {
individual static terminal String line = "-----------------------------------------";

individual void loadResource (String resource) throws IOException {
URL u = this.getClass().getResource(resource);
loadResourceByUrl(u, resource);
}

private void loadResourceWithContextLoader (String resources) throws IOException {
URL u = Thread.currentThread().getContextClassLoader().getResource(resource);
loadResourceByUrl(u, resources);
}

private void loadResourceWithSystemClassLoader (String resource) throws IOException {
URL u = ClassLoader.getSystemClassLoader().getResource(resource);
loadResourceByUrl(u, resource);
}

individual void loadResourceByUrl (URL u, String resource) throws IOException {
System.out.println("-> attempting input resource: "+resource);
if (u != null) {
Cord path = u.getPath();
path = path.replaceFirst("^/(.:/)", "$1");
System.out.println(" absolute resources path found :\northward " + path);
Cord s = new String(Files.readAllBytes(Paths.get(path)));
System.out.println(" file content: "+s);
} else {
System.out.println(" no resources found: " + resource);
}
}

public static void main (String[] args) throws IOException {
Examples a = new Examples();
Arrangement.out.println(line+"\nusing this.getClass().getResource\north"+line);
a.loadResource("test-pkg-resource.txt");
a.loadResource("/test-pkg-resource.txt");
a.loadResource("root-resources.txt");
a.loadResource("/root-resource.txt");

System.out.println(line+"\north using current thread context loader\n"+line);
a.loadResourceWithContextLoader("exam-pkg-resource.txt");
a.loadResourceWithContextLoader("/exam-pkg-resource.txt");
a.loadResourceWithContextLoader("root-resource.txt");
a.loadResourceWithContextLoader("/root-resource.txt");

Arrangement.out.println(line+"\n using ClassLoader.getSystemClassLoader()\n"+line);
a.loadResourceWithSystemClassLoader("examination-pkg-resource.txt");
a.loadResourceWithSystemClassLoader("/test-pkg-resource.txt");
a.loadResourceWithSystemClassLoader("root-resource.txt");
a.loadResourceWithSystemClassLoader("/root-resource.txt");

}
}

The output looks like this:

-----------------------------------------
using this.getClass().getResource
-----------------------------------------
-> attempting input resource: test-pkg-resource.txt
absolute resources path found :
C:/load-resource/out/product/load-resource/com/logicbig/example/examination-pkg-resource.txt file content: test file, local to bundle
-> attempting input resource: /test-pkg-resource.txt
no resource establish: /examination-pkg-resource.txt
-> attempting input resource: root-resource.txt
no resource establish: root-resource.txt
-> attempting input resource: /root-resources.txt
absolute resource path institute : C:/load-resource/out/production/load-resources/root-resource.txt file content: root test file
-----------------------------------------
using current thread context loader
-----------------------------------------
-> attempting input resource: test-pkg-resources.txt
no resource found: test-pkg-resources.txt
-> attempting input resource: /exam-pkg-resource.txt
no resource constitute: /exam-pkg-resource.txt
-> attempting input resource: root-resource.txt
absolute resource path found : C:/load-resource/out/production/load-resource/root-resource.txt file content: root examination file
-> attempting input resource: /root-resource.txt
no resources found: /root-resource.txt
-----------------------------------------
using ClassLoader.getSystemClassLoader()
-----------------------------------------
-> attempting input resource: examination-pkg-resources.txt
no resource constitute: test-pkg-resource.txt
-> attempting input resource: /test-pkg-resources.txt
no resources found: /test-pkg-resources.txt
-> attempting input resource: root-resource.txt
absolute resource path found : C:/load-resources/out/production/load-resource/root-resources.txt file content: root test file
-> attempting input resource: /root-resources.txt
no resource found: /root-resource.txt

In this case we outset created a line which is used later in the plan. Afterwards that we told the program to search for paths using get.Class().getResource, using thread context loader and by using ClassLoader.getSystemClassLoader(). If in 1 of those attempts programm institute a path it would print out that the absolute resource path is institute along with the path, if non information technology would merely say that the resource is not institute.

More to read about handling files:
How to admission files in Java
Read from File in Java
Write to File in Java

harristheassion.blogspot.com

Source: https://xenovation.com/blog/development/java/java-read-file-from-classpath

0 Response to "Read a File From a Url Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel