dynamic path in java application - java

I want to specify the path dynamically. myapp/CopyFolder and myapp/RunFolder's are inside application like myapp/WEB-INF. The code I have given below is in .java file(in eclipse) and in .class file(in tomcat inside myapp/WEB-INF/classname/packagename/). My deployment is in tomcat.
try {
functionNamesObject.Integration(
".txt",
path+"\\CopyFolder",
path+"\\RunFolder",
"app.exe",
"Input.txt"
);
I want path to be dynamic when I call above function. I tried with getResource("MyClass.class") ,new File("").getAbsolutePath(); and System.getProperty("user.dir") but no use. Is there any other way?

You can get the path value as below:
URL resource = getClass().getResource("/");
String path = resource.getPath();
This will return the absolute path to to your myApp/WEB-INF/classes directory.

Related

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

Relative to absolute path in java

I have have a file that I want to use in my project which is in the resources package
src.res
Following what was stated in this answer, I believe that my code is valid.
File fil = new File("/res/t2.nii");
// Prints C:\\res\\t2.nii
System.out.println(fil.getAbsolutePath());
The problem is that I that file is in my projects file not there, so I get an Exception.
How am I suppose to properly convert from relative path to absolute?
Try with directory first that will provide you absolute path of directory then use file.exists() method to check for file existence.
File fil = new File("res"); // no forward slash in the beginning
System.out.println(fil.getAbsolutePath()); // Absolute path of res folder
Find more variants of File Path & Operations
Must read Oracle Java Tutorial on What Is a Path? (And Other File System Facts)
A path is either relative or absolute.
An absolute path always contains the root element and the complete directory list required to locate the file.
For example, /res/images is an absolute path.
A relative path needs to be combined with another path in order to access a file.
For example, res/images is a relative path. Without more information, a program cannot reliably locate the res/images directory in the file system.
Since you are using a Java package, you must to use a class loader if you want to load a resource. e.g.:
URL url = ClassLoader.getSystemResource("res/t2.nii");
if (url != null) {
File file = new File(url.toURI());
System.out.println(file.getAbsolutePath());
}
You can notice that ClassLoader.getSystemResource("res/t2.nii") returns URL object for reading the resource, or null if the resource could not be found. The next line convertes the given URL into an abstract pathname.
See more in Preferred way of loading resources in Java.
validate with
if (fil.exists()) { }
before and check if it really exist. if not then you can get the current path with
System.getProperty("user.dir"));
to validate that you are starting fromt he proper path.
if you really want to access the path you shouldnt use absolut pathes / since it will as explained start from the root of your Harddisk.
you can get the absolut path of the res folder by using this what my poster was writte in the previous answer:
File fil = new File("res");
System.out.println(fil.getAbsolutePath());

How to get the excel file path using java code

String dirPath = fileObj.getParentFile().getAbsolutePath();
system.out.println(dirPath);
I tried this way but its returning the Java Project Path that is Workspace path..
.getParentFile() is probably returning the parent directory, which depending on the location of your file could be the project directory. If fileObj is an object of type File, just try using fileObj.getAbsolutePath() instead.
So try this:
File fileObj = new File("myFile.xls");
String dirPath = fileObj.getAbsolutePath();
System.out.println(dirPath);
This should result in output similar to:
C:/[your project directory]/myFile.xls
JavaDoc for getParentFile():
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#getParentFile()

How to get absolute path to file in /resources folder of your project

Assume standard maven setup.
Say in your resources folder you have a file abc.
In Java, how can I get absolute path to the file please?
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)
You can use ClassLoader.getResource method to get the correct resource.
URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
OR
Although this may not work all the time, a simpler solution -
You can create a File object and use getAbsolutePath method:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
You need to specifie path started from /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath() method of that class.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
There are two problems on our way to the absolute path:
The placement found will be not where the source files lie, but
where the class is saved. And the resource folder almost surely will lie somewhere in
the source folder of the project.
The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.
You can insert the code into yours and see the paths that you have.
To return a file or filepath
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path

Get the filePath from Filename using Java

Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...

Categories