How to access folder near to my application in webapp? - java

my application is under wtpwebapps folder
wtpwebapps->myapp
and my files are under the wtpwebapps->files folder
wtpwebapps->files->file1
wtpwebapps->files->file2
wtpwebapps->files->file3
i've tried
request.getSession().getServletContext().getRealPath();
and got this path
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
when i append
"\files\file1"
to the path and acces that files then it gives me error that
The requested resource is not available
How to resolve this issue?

Try this:
File currentDir=new File(request.getSession().getServletContext().getRealPath())
// or try this instead too:
// File currentDir=new File(".");
File myFile=new File(currentDir,"files\\file1");

You can get the absolute path to your myApp/WEB-INF/classes directory as below:
URL resource = getClass().getResource("/");
String path = resource.getPath();
Now you can manipulate the path string to go to your files:
path = path.replace("your_app_name/WEB-INF/classes/", "");
path = path + "files/file1";
Here path is now referring to file1 present in wtpwebapps->files.

If you append literally \files\file1 this won´t work because backslash is the escape character. Try
/files/file1
Java will convert to the platform path seperator.

Here is the code from a listener ....
System.out.println("Inside contextInitialized()");
System.out.println( servletContextEvent.getServletContext().getRealPath("") );
System.out.println( servletContextEvent.getServletContext().getRealPath("/") );
String filePath = servletContextEvent.getServletContext().getRealPath("/public/file.txt");
File file = new File(filePath);
System.out.println( filePath );
System.out.println( file.exists() );
and its output...
Inside contextInitialized()
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\public\file.txt
true
Note that i have edited the path in between.

Related

Java: Including folder path in the file name for a File object

I am trying to output an object to a file, and the code below works fine.
val myFile = new File(myPath + "_" + myFileName)
val myData = new ObjectOutputStream(new FileOutputStream(myFile))
However, if I want to make myFileName under myPath like:
val myFile = new File(myPath + "/" + myFileName)
val myData = new ObjectOutputStream(new FileOutputStream(myFile))
I got java.io.FileNotFoundException.
Any idea what I might have missed? Thank you!
If folder myPath does not exists the FileNotFoundException will be thrown. You have to create that folder first. You may do it manually or by mkdir() method from File class.
This error is definitely due to missing folder referenced by "mypath" or myFileName.
JDK7 has nice abstraction for path in which you don't have to worry about path separator character (i.e /)
Use Paths
for eg
Path p = Paths.get("c:", myPath ,myFileName)
You can extract file object from path and do whether path exists before starting any processing.

Get directory from classpath (getting a file now)

I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.
URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());
How can I load this way a directory?
It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString().
You need to change below line
File folder = new File(url.toString());
with this line
File folder = new File(url.getPath());
You need path of that folder which will you get from URL.getPath() function.
I hope this is what you need.
If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.
Here is an example:
URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());

How to get and use the path of a folder in eclipse project?

I create a new folder Fold inside my eclipse project Proj. How do I get the path of Fold relative to Proj ? This folder will be used as place to store serialized objects. Will I be able to serialize and de-serialize my code using this relative path ?
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/folder");
or
URL url = getClass().getResource("path/folder");
This code gets the path -
String absolutePath = new File(".").getAbsolutePath();
System.out.println(absolutePath);// Shows you the path of your Project Folder
int last = absolutePath.length()-1;
absolutePath = absolutePath.substring(0, last);//Remove the dot at the end of path
System.out.println(absolutePath);
String filePath = "MyFolderInsideEclipseProject\\file.txt";//You know this
System.out.println(absolutePath + filePath);//Get the full path.

Get Application Path to create a new File

How can I get the Application path of a Project in a String variable LogPath. The LogPath is used later on to create a Log File of the Project. Am using Eclipse for coding.
USE
String AbsolutePath = new File(".").getAbsolutePath();
Explanation : File(".") represents the current directory and getAbsoultePath() returns absolute path to the current directory.
Hope it helps :-)
I would use
String logPath = new File(".").getAbsolutePath();
.. for start.
This call: new File(".").getAbsolutePath() gives you the current working directory of your application. I hope this answers your question.
Which Language are you using?
Java:
File directory = new File (".");
System.out.println ("Current directory's canonical path: " + directory.getCanonicalPath());
System.out.println ("Current directory's absolute path: " + directory.getAbsolutePath());

Get absolute path in Java

I have string:
String s = "~/abc/d.png"
How can I get absolute path of this file?
I've tried:
File file = new File(s);
String absolutePath = file.getAbsolutePath();
But it can't reslove ~ symbol.
Java isn't going to know what the ~ means since it's a shell expansion for your home directory. You can do this before handing it off to File:
s = s.replace("~",System.getProperty("user.home"));

Categories

Resources