I am trying to get absolute file path on java, when i use the following code :
File f = new File("..\\webapps\\demoproject\\files\\demo.pdf")
String absolutePath = f.getAbsolutePath();
It gives the correct file path on 32-bit machine as
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
But when i run the same on 64-bit machine it gives FileNotFound Exception (because of Program Files(x86)), How to get correct path regardless of OS bit. Could anybody please help.
Universal naming convention (UNC) paths, which are used to access network resources, have the following format: A server or host name, which is prefaced by \\ .
Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
Example. If the current directory is C:\Windows, the relative path to the executable for the game of Solitaire, which is located in the current directory, is simply the name of the executable – sol.exe. If the current directory is C:\Windows\System, the relative path to Solitaire is .. \sol.exe.
To find the full absolute path of the current directory, use the pwd command.
I have used below code and it is giving correct file path where i have usedSystem.getProperty("user.dir")
to get the current working directory and System.getenv("ProgramFiles")
to check program files name.
`
String downloadDir = "..\\webapps\\demoproject\\files";
String currentdir = System.getProperty("user.dir");
String programFiles = System.getenv("ProgramFiles");
String filePath = "";
if(programFiles.equals("C:\\Program Files"))
{
filePath = currentdir + "\\" + downloadDir + "\\demo.pdf";
}
else
{
filePath = currentdir + "\\" + "bin"+ "\\" + downloadDir + "demo.pdf";
}
File pdfFile = new File(filePath);
String absolutePath = pdfFile.getAbsolutePath();
System.out.println(absolutePath);
`
After executing below code i am getting the following path-
On 32-bitC:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
On 64-bitC:\Program Files (x86)\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With