This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 6 years ago.
I'm trying to load a configuration file. But it doesn't work my configuration file is placed under WEB-INF folder
and here is my code to load that conf file :
private static final String PROPERTIES_FILE = "/WEB-INF/dao.properties";
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream fichierProperties = classloader.getResourceAsStream(PROPERTIES_FILE);
if (fichierProperties == null) {
throw new DAOConfigurationException("file "+PROPERTIES_FILE+ " not found" );
}
I'm always getting this error file not found, Should make some changes on the build path ??
For simple purpose, try
Put dao.properties inside src folder (where put source code).
Change to
private static final String PROPERTIES_FILE = "dao.properties"; // <-------
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream fichierProperties = classloader.getResourceAsStream(PROPERTIES_FILE);
if (fichierProperties == null) {
throw new DAOConfigurationException("file "+PROPERTIES_FILE+ " not found" );
}
If you put your file inside the WEB-INF directory, You can use context object to read your file as shown if you have access to servlet context
InputStream input = context.getResourceAsStream("/WEB-INF/dao.properties");
Related
This question already has an answer here:
Java File does not exists but File.getAbsoluteFile() exists
(1 answer)
Closed 5 years ago.
It works well "new FileInputStream(f.getAbsoluteFile())"
private byte[] loadFile(String path) throws IOException {
File f = new File("./build/classes/" + path);
try (InputStream is = new FileInputStream(f.getAbsoluteFile())) {
byte[] data = loadFile(is);
return data;
}
}
And "new FileInputStream(f)"
private byte[] loadFile(String path) throws IOException {
File f = new File("./build/classes/" + path);
try (InputStream is = new FileInputStream(f)) {
byte[] data = loadFile(is);
return data;
}
}
throw exception:
java.io.FileNotFoundException: ./build/classes/traces/onmethod/ErrorDuration.class (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
I can't imagine why.
First make sure you run your two programs from the same working directory.
Also, in the first case, your path is resolved to an absolute path first.
For example: /opt/local/myprod/bin/build/classes/traces/onmethod/ErrorDuration.class
Whle FileInputStream uses the 'simple path' of your file (File.getPath())
Depending on your current work directory, your permissions and your symbolic links those two paths can mean two different things.
From the directory you run your program - does this path work ?
ls ./build/classes/traces/onmethod/ErrorDuration.class
Also see:
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
I want to read an XML file that is located inside one of the jars included in my class path. How can I read any file which is included in the jar?
If you want to read that file from inside your application use:
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");
The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".
The InputStream reads the content of your file. You can wrap it into an Reader, if you want.
Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:
Class.getResourceAsStream(resource)
and
ClassLoader.getResourceAsStream(resource)
(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).
The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".
Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:
package com.example;
public class A {
public static void main(String args[]) {
// Class.getResourceAsStream
Object resource = A.class.getResourceAsStream("nested");
System.out.println("1: A.class nested=" + resource);
resource = A.class.getResourceAsStream("/com/example/nested");
System.out.println("2: A.class /com/example/nested=" + resource);
resource = A.class.getResourceAsStream("top");
System.out.println("3: A.class top=" + resource);
resource = A.class.getResourceAsStream("/top");
System.out.println("4: A.class /top=" + resource);
// ClassLoader.getResourceAsStream
ClassLoader cl = A.class.getClassLoader();
resource = cl.getResourceAsStream("nested");
System.out.println("5: cl nested=" + resource);
resource = cl.getResourceAsStream("/com/example/nested");
System.out.println("6: cl /com/example/nested=" + resource);
resource = cl.getResourceAsStream("com/example/nested");
System.out.println("7: cl com/example/nested=" + resource);
resource = cl.getResourceAsStream("top");
System.out.println("8: cl top=" + resource);
resource = cl.getResourceAsStream("/top");
System.out.println("9: cl /top=" + resource);
}
}
The output from the program is:
1: A.class nested=java.io.BufferedInputStream#19821f
2: A.class /com/example/nested=java.io.BufferedInputStream#addbf1
3: A.class top=null
4: A.class /top=java.io.BufferedInputStream#42e816
5: cl nested=null
6: cl /com/example/nested=null
7: cl com/example/nested=java.io.BufferedInputStream#9304b1
8: cl top=java.io.BufferedInputStream#190d11
9: cl /top=null
Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.
Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.
Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}
so it is the behavior of resolveName() that is important.
Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.
Check first your class loader.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = Class.class.getClassLoader();
}
classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");
// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml
A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.
public static void main(String args[]) {
String relativeFilePath = "style/someCSSFile.css";
String zipFilePath = "/someDirectory/someWarFile.war";
String contents = readZipFile(zipFilePath,relativeFilePath);
System.out.println(contents);
}
public static String readZipFile(String zipFilePath, String relativeFilePath) {
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
// if the entry is not directory and matches relative file then extract it
if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
// Read the file
// With Apache Commons I/O
String fileContentsStr = IOUtils.toString(bis, "UTF-8");
// With Guava
//String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
// close the input stream.
bis.close();
return fileContentsStr;
} else {
continue;
}
}
} catch (IOException e) {
logger.error("IOError :" + e);
e.printStackTrace();
}
return null;
}
In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Just for completeness, there has recently been a question on the Jython mailinglist where one of the answers referred to this thread.
The question was how to call a Python script that is contained in a .jar file from within Jython, the suggested answer is as follows (with "InputStream" as explained in one of the answers above:
PythonInterpreter.execfile(InputStream)
This also works on spring
ClassPathResource resource = new ClassPathResource("/file.txt", MainApplication.class); //resources folder
InputStream inputStream = resource.getInputStream();
File file = new File("file.txt");
FileUtils.copyInputStreamToFile(inputStream, file);
This question already has answers here:
How to get a path to a resource in a Java JAR file
(17 answers)
Closed 7 years ago.
I have a propeties file with a path to a file inside my jar
logo.cgp=images/cgp-logo.jpg
This file already exists:
I want to load this file within my project so I do this:
String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());
But then when I do file.exists() I get false. When I check file.getAbsolutePath() it leads to C:\\images\\cgp-logo.jpg
What am I doing wrong?
Well a file inside a jar is simply not a regular file. It is a resource that can be loaded by a ClassLoader and read as a stream but not a file.
According to the Javadocs, getClass().getClassLoader().getResource(property) returns an URL and getFile() on an URL says :
Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.
So for a jar resource it is the same as getPath() that returns :
the path part of this URL, or an empty string if one does not exist
So here you get back /images/cgp-logo.jpg relative to the classpath that does not correspond to a real file on your file system. That also explains the return value of file.getAbsolutePath()
The correct way to get access to a resource is:
InputStream istream = getClass().getClassLoader().getResourceAsStream(property)
You can use the JarFile class like this:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}
#Test
public void testProviderDetails_ValidFile()
{
ClassLoader classLoader = getClass().getClassLoader();
// Throws null pointer exception here
File file = new File(classLoader.getResource("services/src/text/resources/config/test.txt").getFile());
String filePath = file.getAbsolutePath();
}
I want to get the file path which is placed in the
src/test/resources/config folder.
But i am getting null pointer exception as i mentioned above.Can any help me regarding this ??
Is anything i have missed in the above code ?
I have also tried the below codes :
File file = new File(classLoader.getResource("c:/dev/Provider_Services/services/src/text/resources/config/test.txt").getFile()); and
File file = new File(classLoader.getResource("test.txt").getFile());
File file = new File(classLoader.getResource("config/test.txt").getFile());
Got the same error !!
I assume you are using Maven and its default settings.. so,src/test/resources is already in the classpath. So, just give config/test.txt as the parameter in the getresource method. It will work.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I keep getting a java.lang.NullPointerException when trying to open a txt file in eclipse. Basically, this is a main menu, and when you click the "Rules" button, the rules text file should open. Currently, the txt file is located in a package called "Resources" (which is where all of the other img files I've used in making the game are). Here's the code:
private List<String> readFile(String filename)
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream(filename)));
String line;
while ((line = buff.readLine()) != null)
{
records.add(line);
}
buff.close();
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
//action performed
public void actionPerformed(ActionEvent ae) {
JButton b = (JButton)ae.getSource();
if( b.equals(newGameButton) )
{
flag = true;
controller.startGame();
buttonPressed = "newGameBtn";
}
if(b.equals(quitButton))
{
System.exit(0);
}
if(b.equals(ruleButton)){
readFile("../resource/riskRules.txt");
}
}
Appreciate the help!
If "Resources" it's marked as resource in Eclipse. The txt file should be copied to your class path when you build.
As per what I can guess from your code you should be doing something like
Configuration.class.getResourceAsStream("riskRules.txt")
Since your file will be at the root level of your class path.
If for example the file is withing a dir called "text" in your resources you would use something like
Configuration.class.getResourceAsStream("text/riskRules.txt")
There needs to be some level of rudimentary error checking on the result returned from getResourceAsStream before you attempt to use it. Is there a reason you're using getResourceAsStream instead of getResource? If the file exists on disk (I see from your OP that it's because it's in a package, and may not physically exist on the disk), then you can just use that to return the path to it, and create a file object from it.
String path = "/path/to/resource"; // note the leading '/' means "search from root of classpath"
URL fileUrl = getClass().getResource(path);
if (fileUrl != null ) {
File f = new File(fileUrl.toURI());
BufferedReader = new BufferedReader(new FileReader(f));
// do stuff here...
}
else {
// file not found...
}
If you need to pull the file out of the JAR archive, then you can do this:
String path = "/path/to/resource"; // note the leading '/' means "search from root of classpath"
InputStream is = getClass().getResourceAsStream(path);
if (is != null ) {
BufferedReader = new BufferedReader(new InputStreamReader(is));
// do stuff here...
}
else {
// file not found...
}
In the event your resource is not found, you will avoid the NPE and you can properly account for the fact that it's missing.
Note that if you do have your resources in a package (jar), then you cannot use a path to locate it that uses "..", since there is no "relative path" in a jar archive, it's not actually a file on the filesystem.
Your "resources" are located by the relative path you specify in the getResource... method. A leading "/" means to look at the root of your classpath for locating the resource. No leading "/" means to look relative to the location of the class file that you're using to locate the resource.
If your file is in a location called "com.program.resources", and you're trying to locate it from a class called "com.program.someotherpackage.MyClass", then you'd use:
getClass().getResourceAsStream("/com/program/resources/<file.txt>");
to find it.
Here's my example illustrated:
<classpath root>
com
program
resources
file.txt
img.png
someotherpackage
MyClass.class
Generally, it's common practice to leave resources outside your package structure, to avoid confusion when locating them later. Most IDE's have a way to mark your directories as resources, so when the program is compiled, they will be copied to the proper location in the classpath root, and can be found by any class asking for them.