Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 429
Shan Avatar asked Aug 01 '13 04:08

Shan


People also ask

What does \\ mean in Windows path?

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 \\ .

How do I set the path of a file in Windows?

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).

How do I find the relative path of a file in Windows?

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.

Which of these command is using a full absolute path?

To find the full absolute path of the current directory, use the pwd command.


1 Answers

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

like image 50
Shan Avatar answered Sep 21 '22 18:09

Shan