Relative path of my Java server - java

I'm trying to create a file in my server. I have sent a image, and I want to create that Image in a folder of my server, but with relative path.
String filePath = "C:\\Users\\Administrador\\Desktop\\Proyecto\\clienteServidor\\Server\\folder\\image.jpg";
File imageFile = new File(filePath);
...
I'm doing with the absolute path.
Thanks

hard coding a directory is seldom good for coding. What happens if there is a typo in your code. Using a combination of ./ or ./*
or even using
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
This is explained here.

It is doable but, as Dmitry said, it might not work on every server. SecurityManager class should be consulted if your webapp has the privilege to write to that folder. or you will get an exception.
One way to do it is via ServletContext:
URL webAppRoot = this.getServletConfig().getServletContext()
.getResource("/images/new-image.jpg");
This will point to your ${tomcat}/webapps/mywebapp/images/new-image.jpg.
Another way is via ProtectionDomain:
URL runningClassLocation = this.getClass().getProtectionDomain()
.getCodeSource().getLocation();
But this will most likely give you jar:file://...myapp.jar!/my/package/servlet.class.
After you have the URL you convert it to File and append any relative path to your image folder.
UPDATE:
I agree with Jim, and emphasize that doing it like this is just for academic purposes.
Java is not like PHP so you shouldn't have uploads folder inside your web application's folder. Usually this is done by enabling an administrator-level user to specify a file path to a folder reserved for your application's storage needs.

Related

Current directory of a web app in netbeans

I am working on a web app i have java files in it which uses certain files.I want to specify these files using relative path in java so that it doesn't produce mobility issue.But Where should i place a file in a web app so that i can use relative path.? I have tried placing the files under source package, web folder, directly under the web-application.Please help.Thanks in advance
The simplest way to get the current directory of a java application is :
System.out.println(new File(".").getAbsolutePath());
Like that you can consider the given path as the root of your application.
Cheers,
Maxime.
Read the file as a resource. Put it somewhere in the src. For instance
src/resources/myresource.txt
Then you can just do
InputStream is = getClass().getResourceAsStream("/resources/myresource.txt");
Note: if you are using maven, then you are more accustomed to something like this
src/main/resources/myresource.txt
With maven, everything in the main/resources folder gets built to the root, so you would leave out the resources in your path
InputStream is = getClass().getResourceAsStream("/myresource.txt");

Java FileOutputStream: path relative to program folder?

What is the best way to find a path relative to the folder where a java application is "installed"?
I have a class with a static method: public static void saveToFile(String fileName)
When I call it with an absolute path, it works, but what I really want is the relative path to where the application is run from, and a folder.
I have not deployed my application, but right now I want to find a path relative to the (Netbeans) project root, and a folder within called data: ProjectName\data\file.dat. Should I use the File class or make it into a URI or something?
Note that I prefer it to be system-independent and will still work if the application is deployed. Eventually the (relative) pathname will be stored in a properties file.
Sorry if this question is a duplicate, any help is appreciated.
What is the best way to find a path relative to the folder where a java application is "installed"?
OS manufacturers have been saying for a long time not to save files in the application directory.
Note that I prefer it to be system-independent and will still work if the application is deployed.
Instead put the File in a sub-directory of user.home. User home is where it should be possible to establish a file object that can be read or written. It is also a place that is reproducible across runs, and platform independent.
If you deploying as a jar, its possible to obtain the jar file name and path the current code is working in like this:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
(from How to get the path of a running JAR file?)
Here you go:
String path = System.getProperty("user.dir");
To find relative path to current working directory say new File(".").
If you want to know absolute path of current working directory you can write new File(".").getAbsolutePath() or File(".").getAbsoluteFile()`.
I hope this answers your question. I am sorry if I did not understand you correctly.
To get the absolute path to a file use new File().getCanonicalFile().
new FileOutputStream(new File(".\\target\\dataset.xml").getCanonicalFile())

Java: getCodeBase() on non-applet application

I'm trying to create a URL to access a local file like so:
URL myURL = new URL(getCodeBase(), "somefile.txt");
But it throws a NullPointerException when it attempts getCodeBase(). I'm fairly certain that the reason behind this is because the class file that this code belongs to is not an applet. Is there any way I can get the code base without using an applet? I just want to access a local file without having to put the actual directory in (because when others run the application the directory path will obviously not be the same).
I would use the following to be relative to the working directory
URL myURL = new URL("file:somefile.txt");
or
URL myURL = new URL("file", "", "somefile.txt");
or
File file = new File("somefile.txt");
You don't need to get the code base.
If the file resides on your classpath (this includes the path where your classes are deployed), you can access vía the ClassLoader method getSystemResource.
URL myURL = ClassLoader.getSystemResource("somefile.txt");
If somefile.txt is read-only, put it in a Jar that is on the run-time class-path of the application. Access it using:
URL urlToText = this.getClass().getResource("/path/to/somefile.txt");
If it is read/write:
Check a known sub-directory of user.home for the file.
If not there, put it there (extracting it from a Jar).
Read/write to the file with known path.
See How to create a folder in Java posting, which asked very similar question.
As Tomas Narros said above, the proper way to do this is to use the ClassLoader to locate resource files in the Classpath. The path you pass to the ClassLoader is relative to the classpath that was set when you started the Java app.
If you browse the above link, you'll see some sample code showing how to resolve the path to a file in your classpath.

Find conf file regardless how application started

I'm newbie to java.
I have some directory structure
product/
conf/
classes/com/../..
conf/ contains some configuration file, while under classes/ I have my application.
How can I ensure from inside java code that I'm able to find file in conf/ despite way I'm executing it (e.g. from eclipse, from different directories, from crontab etc.).
P.S.
Files in conf/ are not resources, since required to be edited by user.
Is there're way to know where my .class, so I canuse relative path form that directory to reach my directory (e.g. MY_CLASS_DIR/../../../../conf)
I would put the conf directory into the class path. That way you can always find them by:
YourClass.class.getClassLoader().getResource("conf/....");
You can use the absolute path, including the way to product.
Or you may use a configuration setting, by starting your program like
java -DXY_HOME=/some/path/product ...
From the javacode, you use it:
String xyHome = System.getProperty ("XY_HOME")
Or you use a kind of inifile in your home directory, where you specify where to look for the conf-directory.
Rereading your question multiple times, it is unclear to me what your goal is. To find the conf dir independently from where you are (eclipse, crontab, ...)? But the headline asks for the CWD, which is the opposite - the directory, depending on where you are.
Both is possible, but you have to decide what you want.
Its safe to use relative paths than absolute paths. Even if you JAR your classes tomorrow it will work as is,
Put you configuration files in classpath during deployment.(Please note that
project directory structure can be different from that of deployment directory structure)
product/
classes/com/../..
classes/conf/some_conf.properties
Then you can use Apache common configuration to get the URL of file
URL urlOfFile = org.apache.commons.configuration.
ConfigurationUtils.locate("conf/some_conf.properties");
The other alternative you can try is,
URL urlOfFile = <SomeClassFromClassesFolder>.class.
getClassLoader().getResource(resourceFile);
Once you get the URL of your configuration file getting stream out of it very simple,
InputStream stream = urlOfFile.openStream();
Good luck.
For you understanding you can refer the following as well,
http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_IO_CurrentWorkingDirectory
http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_Reflection_WheretheClassloadedfrom
Good luck.
you can find out what is the absolute path of the working dir by:
String str = new File("").getAbsolutePath()

How can I create a new folder in my web-app (for upload photo album) with Grails on Tomcat?

i want to create a photo album.
But I want to organize on the server the albums so I want to create new folders :
/myapp
/myapp/albums
/myapp/albums/1
/myapp/albums/2
...
How can I do that on tomcat with Grails ? It create all new folder in tomcat/bin not in tomcat/webapps/myapp/
When I had to do something similar I defined a root path in my Config.groovy like
environments {
production {
rootPath="/home/user/reports"
}
development {
rootPath="c:\\reports"
}
test {
rootPath="c:\\reports"
}
Then create a directory like the following.
import org.codehaus.groovy.grails.commons.ConfigurationHolder as Conf
tempFile=new File(Conf.config.rootPath+"dirName")
tempFile.mkdir()
I don't do Grails, but since it runs on top of the Servlet API, you may find this answer (a steering in the right direction) useful as well.
First, get a handle of the ServletContext. Normally you would use the GenericServlet-inherited getServletContext() method for this. Then make use of the ServletContext#getRealPath() method to convert a relative web path to an absolute local disk file system path (because that's the only which java.io.File reliably understands).
String absolutePath = getServletContext().getRealPath("albums/1");
File file = new File (absolutePath);
// ...
If you use relative paths in java.io.File stuff, then it will become relative to the current working directory which depends on the way how you startup the server and which indeed may be Tomcat/bin as you experienced yourself.
That said, there's another major problem with this approach: if you create folders in an exploded webapp, they will get lost whenever you redeploy the webapp or even restart the server! Rather create folders outside the webapp's context, in a fixed path somewhere else at the disk file system. Or if you want better portability (but poorer metadata information), then consider storing it in a database instead.

Categories