如何在java中获取当前目录?

Rag*_*aja 4 java linux directory struts2 java-ee

我试图从java获取我的项目的当前目录.我使用以下代码行来获取路径详细信息.

类型1:

File directory = new File (".");
try {
    System.out.println ("Current directory's canonical path: " 
            + directory.getCanonicalPath()); 
    System.out.println ("Current directory's absolute  path: " 
                + directory.getAbsolutePath());
}catch(Exception e) {
    System.out.println("Exceptione is ="+e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

类型2:

String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" +currentDir);
Run Code Online (Sandbox Code Playgroud)

从主类执行上面的代码我得到项目目录.当我从服务器端执行时,得到"当前dir使用System:D:\ Apache Tomcat 6.0.16\bin".但我的项目位于D:\Apache Tomcat 6.0.16\wepapps\SampleStructs.

请给我任何建议,并帮助我解决这个问题.

Gor*_*vic 7

首先,问题的主要原因是当前工作目录与可执行文件的位置之间的差异.您应该知道Linux中的当前工作目录不是可执行文件所在的目录,而是启动程序的当前目录.

举个例子,假设你有一个current打印出当前目录的程序,它位于/home/user/scripts/.

如果你这样做:

cd /home/user/scripts
./current
Run Code Online (Sandbox Code Playgroud)

它将打印出来:/home/user/scripts/ 但是,如果你这样做:

cd /home/user/
scripts/current
Run Code Online (Sandbox Code Playgroud)

输出将是: /home/user/

至于可能的解决方案,我发现其中一些有用的是:

  • 请参阅相对于类路径的项目资源,ClassLoader.getResourceAsStream()有关详细信息,请参阅参考资料
  • 请参阅相对于用户主目录的配置资源,如属性文件等.
  • 将所有其他位置(例如媒体目录路径等)放在上面的配置文件中.
  • 如果所有其他选项都不可用或不实用getClass().getProtectionDomain().getCodeSource().getLocation().getPath().在此处查看有关此方法和一些可能问题的更多信息:如何获取正在运行的JAR文件的路径?