44

我正在创建一个使用 log4j 的 Java 应用程序。我已经给出了配置 log4j 文件的绝对路径以及生成的日志文件的绝对路径(生成此日志文件的位置)。我可以通过以下方式在运行时获取 Java Web 应用程序的绝对路径:

String prefix =  getServletContext().getRealPath("/");

但是在普通 Java 应用程序的上下文中,我们可以使用什么?

4

14 回答 14

57

尝试;

String path = new File(".").getCanonicalPath();
于 2010-10-27T12:15:55.693 回答
38

目前尚不清楚您的要求是什么。我不知道“关于我们正在使用的网络应用程序”是什么意思,如果getServletContext().getRealPath()不是答案,但是:

  • 当前用户的当前工作目录由下式给出System.getProperty("user.dir")
  • 当前用户的主目录由下式给出System.getProperty("user.home")
  • 加载当前类的 JAR 文件的位置由this.getClass().getProtectionDomain().getCodeSource().getLocation().
于 2010-10-27T12:23:33.930 回答
11

那么使用this.getClass().getProtectionDomain().getCodeSource().getLocation()呢?

于 2011-09-17T00:42:44.737 回答
5

由于 a 的应用程序路径JAR和从 an 内部运行的应用程序IDE不同,我编写了以下代码以始终返回正确的当前目录:

import java.io.File;
import java.net.URISyntaxException;

public class ProgramDirectoryUtilities
{
    private static String getJarName()
    {
        return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
                .getName();
    }

    private static boolean runningFromJAR()
    {
        String jarName = getJarName();
        return jarName.contains(".jar");
    }

    public static String getProgramDirectory()
    {
        if (runningFromJAR())
        {
            return getCurrentJARDirectory();
        } else
        {
            return getCurrentProjectDirectory();
        }
    }

    private static String getCurrentProjectDirectory()
    {
        return new File("").getAbsolutePath();
    }

    private static String getCurrentJARDirectory()
    {
        try
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
        } catch (URISyntaxException exception)
        {
            exception.printStackTrace();
        }

        return null;
    }
}

只需打电话getProgramDirectory(),无论哪种方式你都应该很好。

于 2017-04-21T22:45:44.403 回答
4

如果您在谈论 Web 应用程序,则应该使用getRealPathfromServletContext对象。

例子:

public class MyServlet extends Servlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
              throws ServletException, IOException{
         String webAppPath = getServletContext().getRealPath("/");
    }
}

希望这可以帮助。

于 2010-10-27T12:09:12.557 回答
2

我使用这种方法来获取 jar 或 exe 的完整路径。

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

pto.getAbsolutePath());
于 2017-05-15T04:04:36.503 回答
1
new File(".").getAbsolutePath()
于 2010-10-27T12:16:58.110 回答
1

最好将文件保存到 user.home 的子目录中,而不是应用程序的任何位置。可能居住。

Sun 付出了相当大的努力来确保小程序和应用程序。使用 Java Web Start 启动无法确定应用程序。真实路径。这一变化破坏了许多应用程序。如果这些更改扩展到其他应用程序,我不会感到惊讶。

于 2010-10-27T12:23:59.613 回答
1
/*****************************************************************************
     * return application path
     * @return
     *****************************************************************************/
    public static String getApplcatonPath(){
        CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
        File rootPath = null;
        try {
            rootPath = new File(codeSource.getLocation().toURI().getPath());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return rootPath.getParentFile().getPath();
    }//end of getApplcatonPath()
于 2016-07-13T11:52:48.227 回答
0

如果要获取Spring(Servlet)等java web应用程序的真实路径,可以从HttpServletRequest自带的Servlet Context对象中获取。

@GetMapping("/")
public String index(ModelMap m, HttpServletRequest request) {
    String realPath = request.getServletContext().getRealPath("/");
    System.out.println(realPath);
    return "index";
}
于 2018-07-28T14:34:34.657 回答
0

我认为每个人都错过了一个关键问题。

String prefix =  getServletContext().getRealPath("/");

servlet 实例可以在任意多个节点之一上,并且在技术上根本不需要文件系统。

例如,在 Java EE 容器中,应用程序可以从数据库甚至目录服务器加载。应用程序的不同部分也可以在不同的节点上运行。对应用程序之外的世界的访问由应用程序服务器提供。

如果您必须保持与旧版 log4j 的兼容性,请使用 java.util.logging 或 Apache Commons Logging。告诉应用程序服务器日志文件应该去哪里。

于 2021-04-22T14:40:37.343 回答
-1

我的类路径的根目录上有一个文件“cost.ini”。我的 JAR 文件名为“cost.jar”。

以下代码:

  • 如果我们有 JAR 文件,则获取 JAR 文件所在的目录。
  • 如果我们有 *.class 文件,则采用类根目录。

try {
    //JDK11: replace "UTF-8" with UTF_8 and remove try-catch
    String rootPath = decode(getSystemResource("cost.ini").getPath()
            .replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
    showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}

从返回的路径.getPath()具有以下格式:

  • 在 JAR 中:file:/C:/folder1/folder2/cost.jar!/cost.ini
  • 在班上:/C:/folder1/folder2/cost.ini

    如果应用程序以 JAR 格式提供,则每次使用File, 都会导致异常。

  • 于 2019-03-03T11:29:26.010 回答
    -1

    如果您想使用此答案: https ://stackoverflow.com/a/4033033/10560907

    您必须像这样添加导入语句:

    import java.io.File;

    在最开始的java源代码中。

    喜欢这个答案:https ://stackoverflow.com/a/43553093/10560907

    于 2018-11-01T08:49:30.340 回答
    -2

    表达方式

    new File(".").getAbsolutePath();
    

    将为您提供与 JVM 执行关联的当前工作目录。但是,JVM 确实通过

    System.getProperty(propertyName); 
    

    界面。可以在此处找到这些属性的列表。

    这些将允许您以独立于平台的方式引用当前用户目录、临时目录等。

    于 2010-10-27T12:31:10.213 回答