Reputation: 335
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.
Upvotes: 6
Views: 819
Reputation: 335
I have used below code and it is giving correct file path where i have used
System.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-bit
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
On 64-bit
C:\Program Files (x86)\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
Upvotes: 1
Reputation: 3502
I am not aware of your concern.
Just give a try to:
request.getServletContext().getRealPath("/")
It will give you the context path of your application Root folder regardless of underlying platform and you can add required folder or file's relative path (Relative path from application root folder ) with it to get absolute path.
Upvotes: 0