How to Really Read Text File from Classpath in Java

How to really read text file from classpath in Java

With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:

// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

If those aren't working, that suggests something else is wrong.

So for example, take this code:

package dummy;

import java.io.*;

public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}

And this directory structure:

code
dummy
Test.class
txt
SomeTextFile.txt

And then (using the Unix path separator as I'm on a Linux box):

java -classpath code:txt dummy.Test

Results:

true
true

How can I read a file from the classpath in a JAR?

You cant refer the file from jar the way you do it in from resources. Since the file is packaged inside the jar you need to read it as resource.
You have to read the file as resource using classloader.

sample code:

ClassLoader CLDR = this.getClass().getClassLoader();
InputStream inputStream = CLDR.getResourceAsStream(filePath);

If you are using java 8 and above then you can use below code using nio to read your file:

final Path path = Paths.get(Main.class.getResource(fileName).toURI());
final byte[] bytes = Files.readAllBytes(path);
String fileContent = new String(bytes, CHARSET_ASCII);

How to load a text file from classpath to a String[] in Java

Use
getClass().getResourceAsStream(Name)

instead of

new File(getClass().getResource(Name).getFile())

In the end you get:

String content = new Scanner(getClass().getResourceAsStream(Name)).useDelimiter("\\Z").next();

Accessing a resource as a file is always a bad idea as the resource can be inside of a JAR file and therefore not directly accessible as common file. However if you access it as stream you can always access it.

How to read from text files in classpath across directories?

The actual answer depends entirely on how you're building/packaging this.

It looks like a Maven project, in which case the src/xxx/yyy folders aren't in your actual class hierarchy. After building, src/main/resources will be at the root of your classpath, meaning the classpath resource is simply your/folders/and/file.txt.

If it's not a Maven project, then it depends on how you are building it.

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

Read file from classpath with Java 7 NIO

A Path represents a file on the file system. It doesn't help to read a resource from the classpath. What you're looking after is a helper method that reads everything fro a stream (more efficiently than how you're doing) and writes it to a byte array. Apache commons-io or Guava can help you with that. For example with Guava:

byte[] array = 
ByteStreams.toByteArray(this.getClass().getClassLoader().getResourceAsStream(resourceName));

If you don't want to add Guava or commons-io to your dependencies just for that, you can always read their source code and duplicate it to your own helper method.

Java - java.io.File with Classpath

You can do this:

try {
URL resource = getClass().getClassLoader().getResource("demo/test.txt");
if (nonNull(resource)) {
File file = new File(resource.toURI());
// do something
}
} catch (URISyntaxException e) {
LOGGER.error("Error while reading file", e);
}

This answer shows the different between ClassLoader.getSystemResource and getClassLoader().getResource()



Related Topics



Leave a reply



Submit