FileInputStream is Null? - java

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.

Related

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.

InputStream from jar-File returns always null

i know this question has been asked several times, but i think my problem differs a bit from the others:
String resourcePath = "/Path/To/Resource.jar";
File newFile = new File(resourcePath);
InputStream in1 = this.getClass().getResourceAsStream(resourcePath);
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)
On the other hand the InputStream always return null.
I know the javadoc says that the getResourceAsStream() is null if there is no resource found with this name, but the File is there! (obviously, because it's in the File-Object)
Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?
The getResourceAsStream() method doesn't load a file from the file system; it loads a resource from the classpath. You can use it to load, for example, a property file that's packaged inside your JAR. You cannot use it to load a file from the file system.
So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream class.

Reading from src/main/resources gives NullPointerException

In my Maven project, I have a xls file in src/main/resources.
When I read it like this:
InputStream in = new
FileInputStream("src/main/resources/WBU_template.xls");
everything is ok.
However I want to read it as InputStream with getResourceAsStream. When I do this, with or without the slash I always get a NPE.
private static final String TEMPLATEFILE = "/WBU_template.xls";
InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);
No matter if the slash is there or not, or if I make use of the getClassLoader() method, I still get a NullPointer.
I also have tried this :
URL u = this.getClass().getResource(TEMPLATEFILE);
System.out.println(u.getPath());
the console says.../target/classes/WBU_template.xls
and then get my NullPointer.
What am I doing wrong ?
FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.
getResourceAsStream() will load a file path relative from your application's classpath.
When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.
When you use .getClass().getClassLoader().getResource(fileName)
it considers the location of the fileName is the root - in other words bin folder.
The file should be located in src/main/resources when loading using Class loader
In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.
I usually load files from WEB-INF like this
session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")

Loading files within android

Android seems to make life pretty easy for loading resources of certain types. Once I leave the beaten path a little bit, it seems less helpful. I can load in images, sounds and other objects from the assets folder if and only if they are of certain types. If I try to load a binary file of my own format, I get a less than helpful 'file not found' exception, even though listing the directory shows that it is clearly there.
I've tried using the following methods to read a binary file of a custom format from the assets directory:
File jfile = new File("file://android_asset/"+filename); //tried to get the URI of the assets folder
JarFile file = new JarFile("assets/"+filename); //tried assuming the assets folder is root
fd = am.openNonAssetFd( filename); //tried getting my file as an non asset in the assets folder (n.b. it is definitely there)
fs = am.open(filename, AssetManager.ACCESS_BUFFER); //tried loading it as an asset
I'm thinking that there's something fundamental about android file I/O that I don't understand yet. The documentation for asset management seems incomplete and there must be some reason for deliberately making this unintuitive (something to do with security?). So, what's the fool proof, canonical way of loading a binary file of my own format within an android app?
UPDATE:
I tried file:///android_asset/ but still no joy.
String fullfilename = "file:///android_asset/"+filename;
File jfile = new File(fullfilename);
if (jfile.exists())
{
return new FileInputStream(jfile);
}
else
{
return null; //the file does exist but it always says it doesn't.
}
Are there any permissions for the file or in the project manifest that I need?
Thanks
I think the best way to load a file from the Assets folder would be to use AssetManager.open(String filename) - this gives you back an InputStream which you can then wrap in a BufferedInputStream and otherwise call read() to get the bytes. This would work regardless of the file type. What kind of problems have you had with this approach specifically?
I think you have left out the slash as in
File jfile = new File("file:///android_asset/"+filename);
There's three forward slashes, not two. :)
For me the solution was to uninistall the application, clean the project in Eclipse and run it again. The problem was Android couldn't find the new files I put in the asset folder.
I ended up reading this question so I hope this can be helpful to someone else.

Create File object of file from parent directory in java

I have this issue of accessing a file in one of the parent directories.
To explain, consider the following dir structure:-
C:/Workspace/Appl/src/org/abc/bm/TestFile.xml
C:/Workspace/Appl/src/org/abc/bm/tests/CheckTest.java
In the CheckTest.java I want to create a File instance for the TestFile.xml
public class Check {
public void checkMethod() {
File f = new File({filePath value I want to determine}, "TestFile.xml");
}
}
I tried a few things with getAbsolutePath() and the getParent() etc but was getting a bit complicated and frankly I think I messed it up.
The reason I don't want to use "C:/Workspace/Appl/src/org/abc/bm" while creating the File instance is because the C:/Workspace/Appl is not fixed and in all circumstances will be different at runtime and basically I don't want to hard-code.
What could be the easiest and cleaner way to achieve this ?
Thank you.
You should load it from Classpath in this case.
In your CheckTest.java, try
FileInputStream fileIs = new FileInputStream(CheckTest.class.getClassLoader().getResourceAsStream("org/abc/bm/TestFile.xml");
Use System.getProperty to get the base dir or you set the base.dir during application launch
java -Dbase.dir=c:\User\pkg
System.getProperty("base.dir");
and use
System.getProperty("file.separator");
What could be the easiest and cleaner way to achieve this ?
For accessing static resources use:
URL urlToResource = this.getClasS().getResource("path/to/the.resource");
If the resource is expected to change, write it to a sub-directory of user.home, where it is easy to locate later.
First of all, you can't get a reference to the source file path on runtime.
But, you can access the resrources included at your classpath (where you complied .class files will be).
Normally, your compiler will copy the xml file included at your srouce directory into the build directory, so at last, you could end up having something like this:
C:/Workspace/Appl/classes/org/abc/bm/TestFile.xml
C:/Workspace/Appl/classes/org/abc/bm/tests/CheckTest.class
Then, with your classpath pointing to the compiled classes root dir, you get the resources from this directory, using the ClassLoader.getResource method (or the equivalent Class.getResource() method).
public class Check {
public void checkMethod() {
java.net.URL fileURL=this.getClass().getResource("/org/abc/bm/tests/TestFile.xml");
File f=new File( fileURL.toURI());
}
}
One could do this:
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File file = new File(pathOfTheCurrentClass + "/..", "Testfile.xml");
or
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File filePath = new File(pathOfTheCurrentClass);
File file = new File(filePath.getParent(), "Testfile.xml");
But as Tomas Naros points out this gives you the file located in the build path.
Did you try
URL some=Test.class.getClass().getClassLoader().getResource("org/abc/bm/TestFile.xml");
File file = new File(some.getFile());

Categories