FileInputStream in Spring MVC fails to find file - java

I am working on a SpringMVC project which runs a number of automated tests on a database. The access details for this database are located in a .properties file. This file is located within the project directory.
FileInputStream fis = new FileInputStream("batch-dm.properties");
propFile = new Properties();
propFile.load(fis);
As the file is stored in the project directory the FileInputStream should be able to access it no?
If I provide the absolute path e.g.
FileInputStream fis = new FileInputStream("C:/workspace/Project/batch-dm.properties");
It recognises the file and runs properly.
Do I need to sore this file in a different location because it is a Spring MVC project?
Thanks

Just to clear out your mind, try to see what is the value that outputs System.getProperty("user.dir") (let's call it A), this will print the complete absolute path from where your application was initialized, more specifically it will print the directory from where the JVM was started.
If you doesn't supply a parent path to the file that you are trying to open, the (A) path is taken by default and the file is looked inside that directory. So please, have in mind that.
Aditional information
If you absolutely need that file you should include it in your project so you can access it as a resource. Resource is a file that is included in your project and came bundled with the generated .jar or .war for re distribution.
My advice is to put the file in the package and use as a resource as it the safer way to work with external resources that should be shipped with your project.
Take a deeper look at this post for more about practical way of handling resources.

Please refer below link:
https://stackoverflow.com/a/2308388/1358551
You may have to use getResourceAsStream().

Related

Java FileNotFoundException when trying to read txt file from resources folder

I'm trying to read a text file located in src/main/resources/test/file.txt. I'm trying to get the path of the file using String path = getClass().getResource("/text/file.txt").getFile(); but when I try to read it I get a FileNotFoundException. I tried putting many different paths, all of which failed. How can I go about doing this?
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class methods getResource(String) and getResourceAsStream(String) methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream will understand. Whatever you try will give you a FileNotFoundException ... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use getResourceAsStream and use the resulting input stream directly.
You can copy the contents of getResourceAsStream to a temporary file, and then use the pathname of the temporary file.
You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a JarFile and use that API to open an InputStream for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
Try giving complete path of the file from the disk.
C:\Users\MyUser\Desktop\file name with extension

Path not found for a property file in Web application?

My Property file location is WebRoot/WEB-INF/Test/property files/Question.properties
Now I want to load the property file using FileInputStream. So I wrote the below code.
Properties pr = new Properties();
pr.load(new FileInputStream("WebRoot/WEB-INF/Test/property files/Question.properties"));
By the above code I got java.io.FileNotFoundException.I am using myeclipse for my development. Can any one suggest the path to read my properties.
You are opening it relative to the current directory. Do you know what the current directory is? Try creating a:
File f = new File("WebRoot/WEB-INF/Test/property files/Question.properties");
Then printing or debug the absolute path of the File object. This will tell you what file you are actually trying to open (i.e. full path).
However, if you are trying to open a 'resource' bundled with your web app (as suggested by /WEB-INF/ being in the path) this is probably not a good way to do it. One alternative is to build your 'resource' into one of your application's .jar files.
See here, for a related answer:
Refer to a web page inside a jar file
use the method InputStream java.lang.Class.getResourceAsStream(String name) instead, this will work when you run your class within eclipse and outside eclipse. and use the same path as what you have mentioned in your code and append "/" at the front.
Hope this helps !
Do one thing right click on Question.properties file click on the properties get the Location of the file.
Properties pr = new Properties();
pr.load(new FileInputStream("Location of the file"));

Unable to find a file in server, that can be seen in development mode

My GWT project runs nicely in developement mode but when I put it on server it can't find an XML file.
My file is in src/main/webapp and when I do mvn install it shows up in target/<projectname>-1.0-SNAPSHOT
I try to access the file like this:
FileInputStream inputStream = new FileInputStream("testobj.xml");
and it throws
java.io.FileNotFoundException: testobj.xml (The system cannot find the file specified)
really puzzled by it .. haven't found any useful links on this either.
FileInputStream inputStream = new FileInputStream("testobj.xml");
To make that a valid path you have to place the xml in same folder where your class file is there.
And the good practice is that put the file in WEB-INF folder and access the path like
getSevletContext.getRealPath("/WEB-INF/resources/testobj.xml");
You might placed the file in src and it is taking from system path. Once you compile the project, your java files converts to class files and places in WEB-INF/classes folder, where the context has been changed.
To maintain the consistency for both in development mode and live environment access files from WEB-INF folder with real path.
It can be seen in development because testobj.xml is able to be found on the path in development. After your project is packaged and built it needs to be in your WEB-INF folder in the war. It is generally good practices to put your resources in src/main/resources as well, not the root folder.
Whatever you are using for your build will need to copy your resources to WEB-INF when creating a war. If you are using maven see this thread for how to accomplish this: Maven: how to get a war package with resources copied in WEB-INF?
FileInputStream inputStream = new FileInputStream("testobj.xml");
This line tries to access "testobj.xml" in the process's current directory. When you run this within a web app, it'll look for the file within the application server process's current directory. This directory could be anything, and it's unlikely that the file will be there.
The normal way to read resources packaged with the web app is to use the web app's ClassLoader:
InputStream is = getClass().getClassLoader().getResourceAsStream("resources/testobj.xml");
This will automatically search the web application's deployment files for the named file. See this question for more discussion.

How can i find the path of my file in my Java project file?

I put a file inside my Java project file and i want to read it but how can i find the path name with Java.
Here i put it in C driver but i just want to find path by just writing the name of file. Is there a function for it?
FileInputStream fstream1 = new FileInputStream("C:/en-GB.dic");
If the file is inside the jar file generated for your project (or in the classpath used by your project, generally), under the package com.foo.bar, you can load it using
SomeClassOfYourProject.class.getResourceAsStream("/com/foo/bar/en-GB.dic");
If it's not in the classpath, and you launch the application (using java.exe) from the directory c:\baz, and the file is under c:\baz\boom\, the you can load it using
new FileInputStream("boom/en-GB.dic");
Place it in your classpath, If it is a web application WEB-INF/classes/yourfile.ext, if it is a standalone application place it in bin directory of your application (default class directory is bin).
Then you could read by using one of the following ways.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("yourfile.ext");
Or
InputStream in = this.getClass().getResourceAsStream("/yourfile.ext");
You can read online for the differences between above two approaches.

Create a file and store in Java web application folder

I would like to create an xml file and store in a folder within my spring Mvc web application.
I can get the root of my application with request.getContextPath()
but
how do i get the application's relative path so it will work on any machine indipendently by the location of the application's folder?
Like C:/folder/folder/MYAPPLICATIONROOTFOLDER
You want to do this.
First, you need to get the ServletContext. I don't know how this is done in Spring MVC, but it's there somewhere.
Then you can do:
ServletContext ctx = getServletContextFromSpringSomehow();
String path = ctx.getRealPath("/folder/filename.txt");
FileWriter fw = new FileWriter(path);
The key here is ServletContext.getRealPath. It gives you the local file system path of a resource from within your webapp. Observer that you use "/" here, as it's a URL, not a file name. The container will give you a valid file name in return. Note, this only works if your container explodes your WAR, or you deploy an exploded WAR. If the WAR is NOT exploded, you will get a null back from the container.
Also note, this WILL work for non-existent files. The container does not check for the actual existence of the file. But it will be up to you to actually create any missing intermediate directories, etc.
Finally, of course, that even if you get a file path back, doesn't mean you can actually write to that path. That's a OS permission issue outside of the scope of the container.
One solution is to bundle the XML with the clases in the JAR/WAR and then use the getResourceAsStream() to leverage the ClassLoader to locate the file.
If I put the file foo.xml with the classes in com/stackoverflow/example, I could then locate the resources from objects in that bundle with
InputStream is = MyClass.getResourceAsStream( "com/stackoverflow/example" );
and from here process the file with a XML parser or whatever else you wanted to do to read the file.

Categories