Fetching a resource in Java main method - java

I'm trying to open a resource in my Java application by calling MainClass.class.getResource("/Resources/file.extension") and passing it to File's constructor with getPath(). Next, when I initialize a new FileInputStream with the File, I get a FileNotFoundException. The complete stack trace looks this.
java.io.FileNotFoundException: E:\user\Documents\NetBeansProjects\Project name\build\classes\Resources\file.csv (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at my.secret.project.MainClass.main(MainClass.java:27)
Here's my code.
File file = new File(MainClass.class.getResource("/Resources/file.extension").getPath());
...
InputStream in = new FileInputStream(file);

Your whole code can be replaced with simple:
InputStream in = MainClass.class.getResourceAsStream("/Resources/file.extension");
No need to use File. In fact the file on your CLASSPATH might be pointing to some location inside JAR/WAR, which definitely won't work. Have a loot at Class.getResourceAsStream() for details.

Related

Not able to get JSON file from resource folder using relative path

I am trying to get a JSON file form my resource folder in the main method using relative path. The code works using absolute path but this breaks once I build a jar file from my project which is want I want.
public static void main(String[] args) throws FileNotFoundException {
// Read in database
db = Database.read(Thread.currentThread().getContextClassLoader().getResource("JSON/inhabitants.json").toExternalForm());
names = db.getAllNames();
Read calls a method in Database which uses a inputstream to read the file.
public static Database read(String filename) throws FileNotFoundException {
InputStream is = new FileInputStream(filename);
Reader reader = new InputStreamReader(is);
return gson.fromJson(reader, Database.class);
}
The error I am getting is the following :
java.io.FileNotFoundException:
file:/Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json
(No such file or directory) at java.io.FileInputStream.open0(Native
Method) at java.io.FileInputStream.open(FileInputStream.java:195) at
java.io.FileInputStream.(FileInputStream.java:138) at
java.io.FileInputStream.(FileInputStream.java:93) at
Core.Database.read(Database.java:22) at Main.main(Main.java:51) ...
11 more
The file in directory /Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json
does exist however so I have no idea what is going wrong.
Here is my folder structure (Maven basic structure):
Is there a solution which will still able me to deploy it as a jar file ?
EDIT (25/09) : If I use getResourceAsStream instead of getResource, I am getting the following error :
Caused by: java.io.FileNotFoundException: java.io.BufferedInputStream#4f8e5cde (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)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at Core.Database.read(Database.java:22)
at Main.main(Main.java:51)
... 11 more
You have to use getResourceAsStream to read files from within the running jar (which contains the files within src\main\resources)!
Use This,
Resource resource = new classpathResource(json);
new ObjectMapper.readValue(resource.getInputStream(),Object.class);

Can't find specified path when using .. in the middle?

I'm trying to write in a file with a path like this:
D:\abcd\efgh\..\ijkl\file.txt
So I have an File object with such a path, but in the line
FileOutputStream fos = new FileOutputStream(f);
I get this:
java.io.FileNotFoundException: ..\ijkl\file.txt (The system cannot find the path specified)
Does anybody know what's wrong here? Is there a possibility to resolve the path in an absolute path?
Initialisation of the File object:
File f = new File(strImagePath);
strImagePath is built out of different Strings and looks exactly like the path shown above.
Thanks!
According to your code java try to access the folder D:\abcd\ijkl\file.txt as you have place ..\ijkl\file.txt but in your system doesnot have any file on that path. Thus you are getting the error.
Edit: can you please, try using D:\\abcd\\efgh\\../efgh\\ijkl\\file.txt

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.

Getting error saying file won't open in Java...any idea why this is happening?

I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.
String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Name of file is LocalNews.txt in library called News....anyone know why the file will not open?
The file is in the same Java Project that I am working on.
Error: LocalNews.txt (The system cannot find the file specified)
Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.
Found out it was looking in
C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt
But I want it to look in (I believe)
C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt
But if I make the above url a string, I get an error.
String y = "LocalNews.txt";
instead use
String y = "path from root/LocalNews.txt"; //I mean the complete path of the file
Your program can probably not find the file because it is looking in another folder.
Try using a absolute path like
String y = "c:\\temp\\LocalNews.txt";
By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("LocalNews.txt");
Use
System.out.println(System.getProperty("user.dir") );
to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.
Also, try this -
File file = new File (y);
System.out.println(file.getCanonicalPath());
This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.

get File from JAR

I'm using Spring's Resource abstraction to work with resources (files) in the filesystem. One of the resources is a file inside a JAR file. According to the following code, it appears the reference is valid
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
// The path to the resource from the root of the JAR file
Resource fileInJar = resourcePatternResolver.getResources("/META-INF/foo/file.txt");
templateResource.exists(); // returns true
templateResource.isReadable(); // returns true
At this point, all is well, but then when I try to convert the Resource to a File
templateResource.getFile();
I get the exception
java.io.FileNotFoundException: class path resource [META-INF/foo/file.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/m2repo/uic-3.2.6-0.jar!/META-INF/foo/file.txt
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:198)
at org.springframework.core.io.ClassPathResource.getFile(ClassPathResource.java:174)
What is the correct way to get a File reference to a Resource that exists inside a JAR file?
What is the correct way to get a File
reference to a Resource that exists
inside a JAR file?
The correct way is not doing that at all because it's impossible. A File represents an actual file on a file system, which a JAR entry is not, unless you have a special file system for that.
If you just need the data, use getInputStream(). If you have to satisfy an API that demands a File object, then I'm afraid the only thing you can do is to create a temp file and copy the data from the input stream to it.
If you want to read it, just call resource.getInputStream()
The exception message is pretty clear - the file does not reside on the file-system, so you can't have a File instance. Besides - what will do do with that File, apart from reading its content?
A quick look at the link you provided for Resource documentation, says the following:
Throws: IOException if the resource cannot be resolved as absolute file path,
i.e. if the resource is not available in a file system
Maybe the text file is inside a jar? In that case you will have to use getInputStream() to read its contents.
Just adding an example to the answers here. If you need a File (and not just the contents of it) from within your JAR, you need to create a temporary file from the resource first. (The below is written in Groovy):
InputStream inputStream = resourceLoader.getResource('/META-INF/foo/file.txt').inputStream
File tempFile = new File('file.txt')
OutputStream outputStream = new FileOutputStream(tempFile)
try {
IOUtils.copy(inputStream, outputStream)
} catch (IOException e) {
// Handle exception
} finally {
outputStream.close()
}

Categories