Get Application Path to create a new File - java

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());

Related

Directory and Filename Concatenating does NOT work

I am working in Netbeans IDE.
What I want to do is:
Get The directory of the Current Java Application (Ex: "F:\PadhooWorld")
Join a file name to it. (Ex: "\Somestuff.txt")
Check if that File exists (Ex: "F:\PadhooWorld\Somestuff.txt")
Do a if.. else activity
When I tam trying to Join Directory + Filename, it is throwing lots of error messages like Path cannot be converted to string etc . Searching the net the whole day, doesn't yield any simple usable solution
Please specify a very simple solution.
EDIT
I have only 2 lines of code as yet
String AppPath = System.getProperty("user.dir");
String fullPath = AppPath + "\Surabhi.txt";
The First Line resolves alright
The Second line (I tried different variations) No Luck. It is underlined in red. Error hints say stuffs like 'Path cannot be converted to string'..
I cannot RUN the code.
It sounds like you're overthinking it. You can just create a File object with the file name you want (the path to the current directory will be used by default) and then call exists() on it:
File f = new File("filename.txt");
System.out.println(f.getAbsolutePath()); //Just for debug if you want to check the path
if(f.exists()) {
//Whatever
}
Alternatively, if you want to specify the path as well as the file name:
String AppPath = System.getProperty("user.dir");
String fileName = "Surabhi.txt";
File f = new File(AppPath, fileName); //f.getAbsolutePath() will give the concatenated name
if(f.exists()) {
//Whatever
}

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 access folder near to my application in webapp?

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.

linux - cannot view directory created from java

I am using the following piece of code to create a directory in java, under Linux:
String dir = "~/tempDir/";
if (!IOUtils.createDirectory(dir)) {
throw new IOException("could no create the local store directory: "
+ dir );
}
LOGGER.info("local store successfully created.");
The application seems to create the directory, as I get no errors and it is working fine.
The problem is that I cannot see this directory on the disk; I am looking in my home directory.
I need to mention that this is a java web application running under tomcat.
Does anyone have any idea why I cannot see this directory?
This does not work because ~ is expanded by your shell, bash or sh or whatever. This doesn't work from Java.
You have created a directory called ~ in your working directory.
You need to get the user's home directory from the system property user.home and build your path from that.
final File dir = new File(System.getProperty("user.home"), "tempDir");
The following will create a "New Folder" under Home, if a folder with the specified name does NOT exist already
final String homePath = System.getProperty("user.home") + "/";
final String folderName = "New Folder";
File file = new File(homePath + folderName);
if (!file.exists())
file.mkdir();
Another option (a better one I should say) you have is using another constructor of File that takes a parent path and a child path as follows:
final String homePath = System.getProperty("user.home");
final String folderName = "New Folder";
File file = new File(homePath, folderName);
if (!file.exists())
file.mkdir();

Make a path for create a file in Java (Android)

Given a File object how can I create the path for saving it?
I tried file.mkdirs() but for example if the file's path is:
/mnt/sdcard/downloads/myapp/temp/song.mp3
it also creates a folder named "song.mp3" inside temp.
How can I do it correctly?
use this code
File myDir=new File("/sdcard/Download");
myDir.mkdirs();
String fname = "Image.jpg";
File file = new File (myDir,fname);
Just try:
file.getParentFile().mkdirs();
this will create the parent directory.
If I have understand correctly what you need is
File.getParent()
hope it helps
If you just want to extract the path you can use lastIndexOf:
String p = "/mnt/sdcard/downloads/myapp/temp/song.mp3";
System.out.println(p.substring(0,p.lastIndexOf('/')));
Of course, if you already have File object then getParent(), as suggested, will be easier.

Categories

Resources