When I pass File file
to a method I\'m trying to get its full path like file.getAbsolutePath();
I always get the same result no matter which one I use
This quote from the Javadoc might be helpful:
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the
java.io
package always resolve relative pathnames against the current user directory. This directory is named by the system propertyuser.dir
, and is typically the directory in which the Java virtual machine was invoked.
I interpret this so that if you create your File
object with new File("filename")
where filename
is a relative path, that path will not be converted into an absolute path even by a call to file.getAbsolutePath()
.
Update: now that you posted code, I can think of some ways to improve it:
list
and listFiles
return null
for non-directory objects, so we need an extra check for that,listFiles()
again in the inner loop, thus avoiding the need to create new File
objects with hand-assembled paths. (Btw note that appending \\
manually to the path is not portable; the proper way would be to use File.separator
).The end result is
private static void doSomethingToDirectory(File factDir) throws IOException {
if (factDir.isDirectory()) {
for (File file : factDir.listFiles()) {
if (file.isDirectory()) {
for (File child : file.listFiles(new MyFilter())) {
process(child);
}
}
}
}
}
class MyFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.equals(TEMP_COMPARE_FILE);
}
}
Note that this code mimics the behaviour of your original piece of code as much as I understood it; most notably, it finds the files with the proper name only in the direct subdirectories of factDir
, nonrecursively.
I think there is a way it may help you if and only if the file is in the program directory.
first you get the program directory by :
new File(".").getCanonicalPath()
then :
if file
is inside a specific directory like folder\\filename
the full path will be
(new File(".").getCanonicalPath() + "\\folder\\filename")
or if file
is directly inside the program directory:
the full path will be
(new File(".").getCanonicalPath() + "\\filename")
i wish this answer help you :)