getResourceAsStream returns NullpointerException [duplicate] - java

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.

Related

gwt servlet getRessourceAsStream always returns null [duplicate]

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"

Extract resource folder from running jar in Java 7

My resources folder inside my jar includes a directory with several binary files. I am attempting to use this code to extract them:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
This is throwing the error
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
Which comes from
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
in UnixException.java. Even though in Files.java the correct options are passed:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
from Files.copy. Of course there's not! That's why I'm trying to make it. I don't yet understand Path and Files enough to do this right. What's the best way to extract the directory and all its contents?
Confused because the docs for Files.copy claims
By default, the copy fails if the target file already exists or is a symbolic link
(Apparently it fails if the target file doesn't exist as well?)
And lists the possible exceptions, and NoSuchFileException is not one of them.
If you're using Guava:
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
You could of course just chain that all into one line; I declared the variables to make it more readable.
The file that does not exist may actually be the directory you're trying to create the file in.
/home/dan/wkhtmltoimage
Does /home/dan exist? Probably not if you're on a Mac.

FileNotFoundException on linux machine when using getClassLoader().getResource

I made already quite some research on internet for this problem. I had no luck so far. Basically this piece of code works fine on Windows with my Junit test src\test\java\com\project\utils\MyTestCase.java :
URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
final String[] paths = { urlApplicationContext.getFile()};
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths);
This file is located there:
\src\test\resources\applicationContext.xml
However on the Jenkins machine which run on linux I got the following error :
testSimple(com.project.ClientImplTest): IOException parsing XML
document from file
[/data/continuous/workspace/sonar/main_proj/data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml];
nested exception is java.io.FileNotFoundException:
data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml
(No such file or directory)
I already verified that the file /data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml does exist.
Why the getResource() does not find the correct path on Linux. It seems it finds data/continous/... instead of /data/continous/... for some reason ? Therefore FileSystemXmlApplicationContext may return an exception because it cannot find the file.
Thanks
I had the same problem in my project - it was caused by spaces in the path - to handle such cases, you need to use the URL's toURI() method - do following:
ApplicationContext ctx;
URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
if (urlApplicationContext != null) {
File appCtxFile = new File(urlApplicationContext.toURI());
ctx = new FileSystemXmlApplicationContext(new String[]{ appCtxFile.getAbsolutePath() });
} else {
throw new RuntimeException("Cannot find XML file 'applicationContext.xml'");
}
Try to add some debug output. URL has nice toString() method. Thus you'll get where app is looking for file.
It looks like you missed slash at the very beginning. Replace data/continuous/... to /data/continuous/... in your resource loader.
Since I don't have enough rep to upvote or comment or anything I will say what I need to say here lol
Oifan is absolutely right (read answer needs accepting).
Had the same issue on Jenkins. Code was trying to access a file during a test, path had spaces in it, resulted in FileNotFoundException. The file was definitely in the right location.
My testing also showed that the spaces were the culprit. We were just going to rename the project in Jenkins which would have resulted in no more spaces in our directory structure. Then I came across Oifan's answer.
Converting the URL from getResource() to a URI and passing that to File() solved the problem for us too.
BTW, the problem is not isolated to linux. I have seen this behavior on Windows Jenkins slaves as well.
Actually Jenkins does not complain about the applicationContext.xml file, but this one: data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext-hibernate-junit.xml
Why the getResource() does not find the correct path on Linux.
I think you need to look at your code and stacktraces again.
The getResource() method does not throw IOException, or any subclasses of IOException. Not ever.
The exception you are seeing is being thrown by ... something else. And it is pretty clear from the message that the code that throws that exception is not looking for a file called "applicationContext.xml" either.
UPDATE
Even following your correction, it remains an incontravertable fact that getResource() cannot cause a FileNotFoundException. You are looking at the wrong code.

How to automatically create a missing folder? [duplicate]

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)

FileInputStream is Null?

Okay, so this is the line that's returning null. What am I doing wrong while creating this FileInputStream?
FileInputStream fin = new FileInputStream(new File(getClass().getResource("data/levellocks.lv").toURI()));
The only thing that can be null there is getResource("data/levellocks.lv") which is calling the toURI call to fail
Either getClass or getResource could return null. Everything else should succeed or throw an exception.
Unless you really need a file input stream, you line can be simplified to:
InputStream in = getClass().getResourceAsStream("data/levellocks.lv");
Class.getResource() and Class.getResourceAsStream are relative to the package. To get the file relative to the root of the classpath, you can call those methods on the classloader:
InputStream in = getClass().getClassLoader().getResourceAsStream("data/levellocks.lv");
Did you make sure the file is in your binary folder, next to the .class files? Not just in your source folder next to the .java files?
I actually just dealt with this issue (I'm no expert) but try debugging and see where the constructor is trying to resolve the name to. For me, it was the package of the class. So when I put the file in the expected folder, it found it.
Would probably be different for you, as I'm using maven. But I put it in src/main/resources and it couldn't find it. When I put a folder structure in src/main/resources of com.work.hin.terminology.match (which was the package of the class), it found it.

Categories