How to give relative path for my file in java file? - java

I am using tomcat server for my java application(Servlet,jsp).In my servlet page calling one java class function.Actually the java file is written separately and i will call the function written inside it.With in the function, i have to read one config(user defined) file for some purpose.so, i am using File class for that.
But, here i have to give relative path of the config file(user defined).Because, now i am running this application in local windows server.But my live server is based on Linux.So, the file path is changed in linux.
File f1=new File("D:\tomcat\webapp\myapp\WEB-INF\src\point_config.txt"); -- windows
File f1=new File("D:\ravi\tomcat\webapp\myapp\WEB-INF\src\point_config.txt"); -- linux
So, i have to give relative path of the file that is common to both windows and linux machine.
Is there a way to do this?
Please guide me to get out of this issue?

Place your config file under your webapp WEB-INF/classes folder and read like this in code
InputStream is=
YourClassName.class.getResourceAsStream("point_config.txt");

The path of the config file leads into the WEB-INF folder
tomcat\webapp\myapp\WEB-INF\src\point_config.txt
Anything inside WEB-INF is protected and cannot be user-defined once the web application has launched. If you meant to read from a user-defined configuration file from the file system, please use an API like the common configuration API.
If you want to insist on keeping the file inside the WEB-INF folder, use the Class.getResourceAsStream() method to obtain the configuration instead. That would not make the configuration user-defined though.

Related

Sharing a Java Object Stream

I've got a project to do with 2 other classmates.
We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)
My question is now about sharing the object stream.
I want to put the file of the stream in same dropbox shared directory of the code.
BUT, when i initialize the file
File f = new File(PATH);
i must use the path of my computer (C:\User**Alessandro**\Dropbox)
As you can see it is linked to Alessandro, and so to my computer.
This clearly won't work on another PC.
How can tell the compiler to just look in the same directory of the source code/.class files?
You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:
URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());
Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.
Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.
As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.

How to give path in Linux to read data from a file in Java

I have a java class like below which reads data from properties file,
java class and properties file both are same directory
FileInputStream fis = new FileInputStream("MyProp.properties");
Then it is compiled success fully and created war file.
This war file i deployed in server, then running properly in windows
Same war file i deployed in another server in Linux, then it is giving exception as
FileNotFoundException
If the file is outside your war, I recommend using a fully qualified path instead of just a relative path. If you need to run in both Windows and Unix-y environments, first detect the operating system like so:
System.getProperty("os.name");
Then set the path accordingly.
However, if the file is in your war, just read it from the classpath like so:
getClass().getClassLoader().getResourceAsStream("MyProp.properties")
or:
getClass().getResourceAsStream("/MyProp.properties");
See this for more details: How to really read text file from classpath in Java

The correct place to put the config file in Eclipse

I have created a Dynamic Web Project in Eclipse and I have a following Java statement that needs to read a config file:
Document doc= new SAXReader().read(new File(ConstantsUtil.realPath+"appContext.xml"));
Basically, ConstantsUtil.realPath will return an empty string.
I tried putting "appContext.xml" under both "src" folder and under "WEB-INF" folder. However, I will always get the following error:
org.dom4j.DocumentException: appContext.xml (The system cannot find the file specified)
I am really confused: in Eclipse, where is the correct place to put my config xml file?
Thanks in advance.
Your concrete problem is caused by using new File() with a relative path in an environment where you have totally no control over the current working directory of the local disk file system. So, forget it. You need to obtain it by alternate means:
Straight from the classpath (the src folder, there where your Java classes also are) using ClassLoader#getResourceAsStream():
Document doc= new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream("appContext.xml"));
Straight from the public webcontent (the WebContent folder, there where /WEB-INF folder resides) using ServletContext#getResourceAsStream():
Document doc= new SAXReader().read(servletContext.getResourceAsStream("/WEB-INF/appContext.xml"));
The ServletContext is in servlets available by the inherited getServletContext() method.
See also:
Where to place and how to read configuration resource files in servlet based application?
getResourceAsStream() vs FileInputStream
What does servletcontext.getRealPath("/") mean and when should I use it
You can embed your config files into your jar/war files
InputStream is = MyClass.class.getResourceAsStream("/com/site/config/config.xml");
You could either create a folder with all your configurations and reference it on the class path of the web application when published on the server, or place them under the WebContent folder, in both cases you need to reference them relatively.
There can be multiple places where you could place your property files. The selection of the location depends on the architeture of the project.
Commonly used location are:
/YourProjectRootFolder/src/main/webapp/WEB-INF/properties/XYZ.properties
: in the same folder where you have your java class files.
YourProjectConfFolderNAme/src/main/resources/XYZ.properties: here all the property files are kept in a seperate location than your project class files.
Both are the same as you need to move all your property files to you server's conf folder.

Access a file from a web service

I am using netbeans to create a web service and using Glassfish as the server to test it within netbeans.
I have a file that i wish the web service to be able to read data from and possibly write to it. But where do i put the file. If 'course' is my netbeans project root i have tried placing the file in the following locations:
\Course
\Course\xml-resources\jaxb\FlightRequest
\Course\web
\Course\web\WEB-INF
\Course\src\java\org\me\FBooking
\Course\build\web
\Course\build\web\WEB-INF
\Course\build\web\WEB-INF\classes
and tried accessing it in the web service in my unmarshalling code using (as the file i am trying to access is an xml document):
un = (AvailableFlights) unmarshaller.unmarshal(new java.io.File("AvailableFlights.xml"));
But it cant find the file
So where am i supposed to place it?
If you need to write to the file, you should locate the file outside of your deployable code.
If you only need read-only access, putting the file in web/ will make the file accessible from a web browser. That may not be what you want.
If you put the file under WEB-INF/classes, it will be accessible to your code, but not publicly exposed.
Your code fragment for accessing the file will only work for files on the file system, and not for files you deploy as part of the WAR, so you need to look into other ways of loading the file if you decide to package it as part of your WAR.
Take a look at
getClass().getResourceAsStream("file")
which should be able to read from files within a WAR file. (Haven't tested it right now..) But this is only for reading from the file.

Java file path in web project

I need to access the resource files in my web project from a class. The problem is that the paths of my development environment are different from the ones when the project is deployed.
For example, if I want to access some css files while developing I can do like this:
File file = new File("src/main/webapp/resources/styles/some.css/");
But this may not work once it's deployed because there's no src or main directories in the target folder. How could I access the files consistently?
You seem to be storing your CSS file in the classpath for some unobvious reason. The folder name src is typical as default name of Eclipse's project source folder. And that it apparently magically works as being a relative path in the File constructor (bad, bad), only confirms that you're running this in the IDE context.
This is indeed not portable.
You should not be using File's constructor. If the resource is in the classpath, you need to get it as resource from the classpath.
InputStream input = getClass().getResourceAsStream("/main/webapp/resources/styles/some.css");
// ...
Assuming that the current class is running in the same context, this will work regardless of the runtime environment.
See also:
getResourceAsStream() vs FileInputStream
Update: ah, the functional requirement is now more clear.
Actually I want to get lastModified from the file. Is it possible with InputStream? –
Use getResource() instead to obtain it as an URL. Then you can open the connection on it and request for the lastModified.
URL url = getClass().getResource("/main/webapp/resources/styles/some.css");
long lastModified = url.openConnection().getLastModified();
// ...
If what you're looking to do is open a file that's within the browser-visible part of the application, I'd suggest using ServletContext.getRealPath(...)
Thus:
File f = new File(this.getServletContext().getRealPath("relative/path/to/your/file"));
Note: if you're not within a servlet, you may have to jump through some additional hoops to get the ServletContext, but it should always be available to you in a web environment. This solution also allows you to put the .css file where the user's browser can see it, whereas putting it under /WEB-INF/ would hide the file from the user.
Put your external resources in a sub-directory of your project's WEB-INF folder. E.g., put your css resources in WEB-INF/styles and you should be able to access them as:
new File("styles/some.css");
Unless you're not using a standard WAR for deployment, in which case, you should explain your setup.
Typically resource files are placed in your war along with your class files. Thus they will be on the classpath and can be looked up via
getClass.getResource("/resources/styles/some.css")
or by opening a File as #ig0774 mentioned.
If the resource is in a directory that is not deployed in the WAR (say you need to change it without redeploying), then you can use a VM arg to define the path to your resource.
-Dresource.dir=/src/main/webapp/resources
and do a lookup via that variable to load it.
In Java web project, the standard directory like:
{WEB-ROOT} /
/WEB-INF/
/WEB-INF/lib/
/WEB-INF/classes
So, if you can get the class files path in file system dynamic,
you can get the resources file path.
you can get the path ( /WEB-INF/classes/ ) by:
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
so, then the next ...

Categories

Resources