This question already has answers here:
getResourceAsStream returns null
(26 answers)
Closed 6 years ago.
I have this peace of code to load a text file inside of a servlet:
String lFileName = mServletContext.getRealPath(mFile);
InputStream lInputStream = mServletContext.getResourceAsStream(lFileName);
InputStream lInputStream2 = mServletContext.getResourceAsStream(mFile);
Both InputStream's are null. I have absolutly no idear why.
The value of mFile is "file.txt".
The value of lFile is "C:\development\workspace\MyGwtApp\war\file.txt".
if I navigate with my explorer to that directory the file file.txt is in it...!
I test my gwt application with the super dev mode.
Compile the gwt app runs without problems.
Do you see the problem?
getResourceAsStream definition
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.
This means that you can read mFile if it exists in your classpath like under WEB-INF/classes. So place your file in your src directory where your java classes exists and look if the file comes to the classes directory and just use its name to get it as resource. Example: filename = "file.txt"
Related
This question already has answers here:
How to read several resource files with the same name from different JARs?
(2 answers)
Closed 4 months ago.
In my application, several libraries are assembled.
Whenever those libraries comes with resources having a same name, getResourceAsStream("myfile") seems to return a stream to whatever file come first.
This is true for any file, including Resource bundles.
In the following example, a library with a MyMibrary class has a file called "config.properties". And does
InputStream is = MyLibrary.class.getResourceAsStream("/config.properties")
When called in a standalone context, the right config file is used.
But when loaded as a dependency from an application having its own "config.properties", the same statement returns the config file of the application instead of the one of the library.
The same applies also for ResourceBundles (which is using getResourceAsStream too) :
If both the library and the application are using Resource bundles named the same way, when called from the application, the library will be using the application resource bundle instead of its own.
My question is how to instruct getResourceAsStream (especially in the context of Resource bundle loading) to use the right resource ?
EDIT: this question differs partially from How to read several resource files with the same name from different in the way the latter question deals only with resources while my question deals also with ResourceBundles.
you need getResources. Note the plural. Unfortunately, whilst MyLibrary.class.getResource is right, class does not have the getResources method copied over from ClassLoader. So, you do have to go via classloader. This is annoying, because in admittedly exotic (Agents, bootstrap classes) situations, MyClass.class.getClassLoader() will be null, so then you need to write code to defer to the system loader instead. For bonus annoyance, the method predates iterators, so it returns an Enumeration instead.
Thus, the full treatment:
ClassLoader cl = MyClass.class.getClassLoader();
if (cl == null) cl = ClassLoader.getSystemClassLoader();
var resources = cl.getResources("config.properties"); // No slash! See footnote 1
while (resources.hasNextElement()) {
URL resource = resources.nextElement();
try (var in = resource.openStream()) {
// yay we can read it now!
}
}
In admittedly really exotic context
[1] Loading via the classloader already starts at the classloader's root, so the leading slash is not required. In fact, if you use it, it'll fail. So, MyClass.class.getLoader().getResource("foo") is the same as MyClass.class.getResource("/foo"), except that the first snippet fails in agent/bootstrap situations.
This question already has answers here:
getResourceAsStream() is always returning null [duplicate]
(7 answers)
Closed 6 years ago.
In Spring, I want to get the image to display on my browser. The image is located in my main project i.e.
> myproject
- src
- target
- img.png
This means that img.png is in the root so I dont supply any path but it returns a NullPointerException. I tried adding the image in src and I changed path to src\img.png but still gave NPE.
Please note, this project is using Maven.
Stack Trace:
java.lang.NullPointerException: null
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792) ~[commons-io-2.4.jar:2.4]
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769) ~[commons-io-2.4.jar:2.4]
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744) ~[commons-io-2.4.jar:2.4]
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:462) ~[commons-io-2.4.jar:2.4]
Here is the code I use:
InputStream in = DataService.class.getResourceAsStream("img.png");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
result.setData(new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED));
Comments on this question being marked for closure:
The question is related to programming as the API getResourceAsStream says this:
Returns
A URL object or null if no resource with this name is found
My code was returning null even when I tried adding img.png to different locations.
This question is not a duplicate of this: getResourceAsStream() is always returning null
The answer in that question says that the file must be in the same directory as this but in this question, even though I added the image to the same location where class DataService was, it did not work.
The issue here is that /src is probably the root of classpath (it depends on how you compile the project), and so you should put the img.png to src folder and the following code would work
DataService.class.getResourceAsStream("img.png");
Generally the getResourceAsStream() looks for the files from the root of classpath.
When the project setup is done using Maven, adding the image to resources folder worked. Nothing from the code changed:
DataService.class.getClassLoader().getResource("img.png")
you just need to do a small change, it's getResourceAsStream("/img.png") not getResourceAsStream("img.png").
I hope this will help.
This question already has answers here:
Method in Java to create a file at a location, creating directories if necessary?
(3 answers)
Closed 1 year ago.
In java, I need to write a string into a new file, like 'c:\test\upload\myfile.txt', if the 'upload' folder is not existing, it will automatically create it. how to do it ? Apache Commons IO has this API ?
File file = new File(...);
file.mkdirs(); //for several levels, without the "s" for one level
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("...");
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
Returns:
true if and only if the directory was created, along with all necessary parent directories; false otherwise
See File.mkdirs() and File.mkdir()
In addition to the accepted answer, since the question also mentioned the library Apache Common IO, I report in the following a solution by using this nice library:
File file = new File("... the directory path ...");
FileUtils.forceMkdir(file);
This solution uses the class FileUtils, from package org.apache.commons.io and the method forceMkdir, that "Makes a directory, including any necessary but nonexistent parent directories".
new File(fileToSave.getParent()).mkdirs();
It returns a boolean to check if the making succeeded (will fail if the disk is full or if a file exists with the name 'upload', etc)
This question already has answers here:
How to create a folder in Java?
(8 answers)
Closed 3 years ago.
I tried to use the File class to create an empty file in a directory like "C:/Temp/Emptyfile".
However, when I do that, it shows me an error : "already made folder Temp". Otherwise, it won't create one for me.
So, how do I literally create folders with java API?
Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
file not found exception in jar
hi
I have one class
and in that i have one file
Document doc = db.parse(element.xml);
but when i create jar it is not getting loaded,
so please tell me is there any other way to give path for file,
so i can run my jar
Use class loader to load any resource from class path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/ensarm/niidle/web/social/sites/sitelist.xml");
db.parse(input);
db.parse(Foo.class.getResource("/com/ensarm/niidle/web/social/sites/sitelist.xml").toString());
Where Foo is the class in which you are writing this code which is in the same jar
Call getResourceAsStream and read the data from the stream:
db.parse(Foo.class.getResourceAsStream("/com/ensarm/niidle/web/social/sites/sitelist.xml"));
You should always prefer to use streams to read the data rather than expecting there to be a particular file.
User ClassLoader.getSystemResource("root/src/com/ensarm/niidle/web/social/sites/sitelist.xml").getPath(); to point to xml's or any resource files..
Note : You must add xml file location to Classpath . (-Djava.class.path="C:\project\resources" ) where xml's are present at C:\project\resources
ClassLoader loadClass = Thread.currentThread().getContextClassLoader() ;
InputStream in =
new InputStreamReader(loadClass.getResourceAsStream("com/ensarm/niidle/web/social/sites/sitelist.xml") );