gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:02 26 4
gpt4 key购买 nike

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

File f = new File("..\\webapps\\demoproject\\files\\demo.pdf")  
String absolutePath = f.getAbsolutePath();

它在 32 位机器上给出正确的文件路径为

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

但是当我在 64 位机器上运行相同的程序时,它给出了 FileNotFound 异常(因为 Program Files(x86)),如何获得正确的路径而不考虑操作系统位。有人可以帮忙吗?

最佳答案

我使用了下面的代码,它给出了我使用的正确文件路径
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);

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

在 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

关于java - 如何获取文件的绝对路径取决于 windows 32 位或 64 位机器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17985316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com