如何获取文件的绝对路径取决于Windows 32位或64位机器

Sha*_*han 6 java

我试图在java上获取绝对文件路径,当我使用以下代码时:

File f = new File("..\\webapps\\demoproject\\files\\demo.pdf")  
String absolutePath = f.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

它在32位计算机上提供正确的文件路径

C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf 
Run Code Online (Sandbox Code Playgroud)

但是当我在64位机器上运行相同时它会给出FileNotFound Exception(因为Program Files(x86)),如何获得正确的路径而不管OS位.请有人帮忙吗

Sha*_*han 1

我使用了下面的代码,它给出了正确的文件路径,我用它
System.getProperty("user.dir")来获取当前工作目录并System.getenv("ProgramFiles")检查程序文件名。

`

    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);
Run Code Online (Sandbox Code Playgroud)

`
执行下面的代码后,我得到以下路径-

在 32 位上
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf

在 64 位上
C:\Program Files (x86)\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf