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 either absolute or canonical path PATH_TO_MY_WORKSPACE/projectName/filename and it is not there, how can I get exact location of the file?
Thank you
DETAILS:
Here is some code and this solutions(its bad but its working):
private static void doSomethingToDirectory(File factDir) throws IOException {
File[] dirContents = factDir.listFiles();
if(factDir.isDirectory() && dirContents.length > 0){
for (int i = 0; i < dirContents.length; i++) {
for (String str : dirContents[i].list()) {
if(str.equals(TEMP_COMPARE_FILE)){
process(new File(dirContents[i].getAbsolutePath() + "\\" + str));
}
}
}
}
}
I’m looping trough directories where factDir is src/main, I’m seeking toBeProcessed.txt files only that is TEMP_COMPARE_FILE value and I’m sending them to process method which reads the file and does processing of it.
If someone could better solution I’d be greatful
This quote from the Javadoc might be helpful:
I interpret this so that if you create your
Fileobject withnew File("filename")wherefilenameis a relative path, that path will not be converted into an absolute path even by a call tofile.getAbsolutePath().Update: now that you posted code, I can think of some ways to improve it:
listandlistFilesreturnnullfor non-directory objects, so we need an extra check for that,listFiles()again in the inner loop, thus avoiding the need to create newFileobjects with hand-assembled paths. (Btw note that appending\\manually to the path is not portable; the proper way would be to useFile.separator).The end result is
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.