How to get the absolute path to a file depends on the windows of a 32-bit or 64-bit machine

I am trying to get the absolute file path in 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 a 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 a 64-bit machine, it gives a FileNotFound Exception (due to program files (x86)), How to get the correct path, regardless of the operating system bit. Someone can help.

+6
source share
2 answers

I used the code below and it gives the correct path to the file where I used System.getProperty("user.dir") to get the current working directory and System.getenv("ProgramFiles") to check the program file 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 the below code, I get the following path:

In 32-bit version
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf

In the 64-bit version
C:\Program Files (x86)\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf

+1
source

I do not know about your concern.

Just try:

request.getServletContext().getRealPath("/")

It will give you the path to the context of your root folder of your application, regardless of the underlying platform, and you can add the desired path to the folder or file (relative path from the root folder of the application) to get the absolute path.

0
source

Source: https://habr.com/ru/post/950778/


All Articles