80

我最近搜索了如何在 Java 中获取应用程序的目录。我终于找到了答案,但我需要的时间出奇的长,因为搜索这样一个通用术语并不容易。我认为编制一份如何用多种语言实现这一目标的列表是个好主意。

如果您(不)喜欢这个想法,请随意赞成/反对,如果您喜欢,请贡献

澄清:

包含可执行文件的目录和当前工作目录pwd在 Unix 下给出)之间有一个很好的区别。我最初对前者感兴趣,但也可以随意发布确定后者的方法(澄清你的意思)。

4

21 回答 21

59

In Java the calls

System.getProperty("user.dir")

and

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

return the current working directory.

The call to

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that yielded the current class if you're running directly from the filesystem.

Example:

  1. Your application is located at

     C:\MyJar.jar
    
  2. Open the shell (cmd.exe) and cd to C:\test\subdirectory.

  3. Start the application using the command java -jar C:\MyJar.jar.

  4. The first two calls return 'C:\test\subdirectory'; the third call returns 'C:\MyJar.jar'.

When running from a filesystem rather than a JAR file, the result will be the path to the root of the generated class files, for instance

c:\eclipse\workspaces\YourProject\bin\

The path does not include the package directories for the generated class files.

A complete example to get the application directory without .jar file name, or the corresponding path to the class files if running directly from the filesystem (e.g. when debugging):

String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

if (applicationDir.endsWith(".jar"))
{
    applicationDir = new File(applicationDir).getParent();
}
// else we already have the correct answer
于 2009-03-24T07:17:06.977 回答
22

.NET (C#, VB, ...)中,您可以查询当前Assembly实例的Location. 但是,这会附加可执行文件的文件名。以下代码清理路径(using System.IOusing System.Reflection):

Directory.GetParent(Assembly.GetExecutingAssembly().Location)

或者,您可以使用提供的信息AppDomain来搜索引用的程序集:

System.AppDomain.CurrentDomain.BaseDirectory

VB 允许通过My命名空间使用另一个快捷方式:

My.Application.Info.DirectoryPath
于 2008-10-20T11:07:58.880 回答
9

Windows中,使用 WinAPI 函数GetModuleFileName()。为模块句柄传入 NULL 以获取当前模块的路径。

于 2008-10-20T12:24:31.627 回答
7

Python

path = os.path.dirname(__file__)

这将获取当前模块的路径。

于 2008-10-20T11:27:46.000 回答
5

Objective-C Cocoa(Mac OS X,我不知道 iPhone 的特性):

NSString * applicationPath = [[NSBundle mainBundle] bundlePath];
于 2009-03-24T15:43:00.020 回答
4

Java中,有两种方法可以找到应用程序的路径。一是雇用System.getProperty

System.getProperty("user.dir");

另一种可能性是使用java.io.File

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

还有一种可能使用反射:

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
于 2008-10-20T11:07:42.420 回答
4

在 VB6 中,您可以使用该App.Path属性获取应用程序路径。

\请注意,当应用程序位于驱动器的根目录中时,这不会有尾随EXCEPT。

在 IDE 中:

?App.Path
C:\Program Files\Microsoft Visual Studio\VB98
于 2012-07-31T10:34:42.500 回答
4

.Net中你可以使用

System.IO.Directory.GetCurrentDirectory

获取应用程序的当前工作目录,特别是在 VB.NET 中,您可以使用

My.Application.Info.DirectoryPath

获取exe的目录。

于 2010-10-28T17:38:56.390 回答
3

Libc
在 *nix 类型环境中(在 Windows 中也是 Cygwin):

  #include <unistd.h>

   char *getcwd(char *buf, size_t size);

   char *getwd(char *buf); //deprecated

   char *get_current_dir_name(void);

见手册页

于 2008-10-20T12:25:06.820 回答
3

德尔福

在 Windows 应用程序中:

Unit Forms;
path := ExtractFilePath(Application.ExeName);

在控制台应用程序中:

与语言无关,第一个命令行参数是完全限定的可执行文件名:

Unit System;
path := ExtractFilePath(ParamStr(0));
于 2008-10-20T11:23:19.643 回答
2

bash中,'pwd' 命令返回当前工作目录。

于 2008-10-20T11:15:53.077 回答
2

PHP中:

<?php
  echo __DIR__; //same as dirname(__FILE__). will return the directory of the running script
  echo $_SERVER["DOCUMENT_ROOT"]; // will return the document root directory under which the current script is executing, as defined in the server's configuration file.
  echo getcwd(); //will return the current working directory (it may differ from the current script location).
?>
于 2011-12-14T04:30:56.767 回答
2

Unix

在 unix 中,可以找到使用环境变量启动的可执行文件的路径。它不一定是绝对路径,因此您需要将当前工作目录(在 shell: 中pwd)和/或 PATH 变量与环境的第 0 个元素的值结合起来。

但是,该值在 unix 中是有限的,因为例如可以通过符号链接调用可执行文件,并且只有初始链接用于环境变量。一般来说,如果 unix 上的应用程序将其用于任何有趣的事情(例如加载资源),它们就不是很健壮。在 unix 上,通常对事物使用硬编码的位置,例如/etc指定资源位置的配置文件。

于 2008-10-20T12:15:57.837 回答
2

Tcl中

当前脚本的路径:

set path [info script]

Tcl 外壳路径:

set path [info nameofexecutable]

如果您需要其中任何一个的目录,请执行以下操作:

set dir [file dirname $path]

获取当前(工作)目录:

set dir [pwd]
于 2010-08-11T16:09:42.397 回答
2

Android

getApplicationInfo().dataDir;

要获得 SD 卡,我使用

Environment.getExternalStorageDirectory();
Environment.getExternalStoragePublicDirectory(String type);

后者用于存储特定类型的文件(音频/电影等)。您在 Environment 类中有这些字符串的常量。

基本上,对于与应用程序相关的任何事情,使用 ApplicationInfo 类,对于与 SD 卡/外部目录中的数据相关的事情,使用 Environment 类。

文档: ApplicationInfo环境

于 2012-02-20T20:08:19.823 回答
2

爪哇:

在所有系统(Windows、Linux、Mac OS X)上只对我有用:

public static File getApplicationDir() 
{
    URL url = ClassLoader.getSystemClassLoader().getResource(".");
    File applicationDir = null;
    try {
        applicationDir = new File(url.toURI());
    } catch(URISyntaxException e) {
        applicationDir = new File(url.getPath());
    }

    return applicationDir;
}
于 2016-09-06T11:41:06.103 回答
1

Ruby中,以下代码段返回当前源文件的路径:

path = File.dirname(__FILE__)
于 2008-10-20T11:37:40.287 回答
1

CFML中有两个函数用于访问脚本的路径:

getBaseTemplatePath()
getCurrentTemplatePath()

调用 getBaseTemplatePath 会返回“base”脚本的路径——即 Web 服务器请求的路径。
调用 getCurrentTemplatePath 返回当前脚本的路径 - 即当前正在执行的脚本。

两个路径都是绝对的,并且包含脚本的完整目录+文件名。

要确定只是目录,请使用getDirectoryFromPath( ... )结果上的函数。

因此,要确定应用程序的目录位置,您可以执行以下操作:

<cfset Application.Paths.Root = getDirectoryFromPath( getCurrentTemplatePath() ) />

onApplicationStart活动内部为您Application.cfc



要确定运行 CFML 引擎的应用服务器所在的路径,您可以使用 cfexecute 访问 shell 命令,因此(请记住上面关于 pwd/etc 的讨论)您可以执行以下操作:

Unix:

<cfexecute name="pwd"/>

对于 Windows,创建一个pwd.bat包含 text @cd,然后:

<cfexecute name="C:\docume~1\myuser\pwd.bat"/>

(使用 的variable属性cfexecute来存储值而不是输出到屏幕。)

于 2008-12-14T22:33:48.550 回答
1

我发布了https://github.com/gpakosz/whereami,它解决了 C 中的问题并为您提供:

  • 当前可执行文件的路径
  • 当前模块的路径(从共享库调用时与可执行文件的路径不同)。

它在 Windows 上使用,在 Linux 和 AndroidGetModuleFileNameW上解析并在 Mac 和 iOS 上使用。/proc/self/maps_NSGetExecutablePathdladdr

于 2015-01-28T16:54:52.807 回答
1

在 cmd(Microsoft 命令行 shell)中

您可以使用 %* 获取脚本的名称(可能与 pwd 相关)

这将获取脚本目录:

set oldpwd=%cd%
cd %0\..
set app_dir=%pwd%
cd %oldpwd%

如果你发现任何错误,你会的。然后请修复或评论。

于 2012-07-03T09:40:34.000 回答
0

注意回答上面关于 Mac OSX 的“20”:如果 JAR 可执行文件通过 OSX JAR BUNDLER 转换为“应用程序”,那么 getClass().getProtectionDomain().getCodeSource().getLocation(); 将不会返回应用程序的当前目录,但会将应用程序的内部目录结构添加到响应中。这个应用程序的内部结构是/theCurrentFolderWhereTheAppReside/Contents/Resources/Java/yourfile

也许这是Java中的一个小错误。无论如何,必须使用方法一或二来获得正确答案,即使应用程序已启动,例如通过位于不同文件夹或桌面上的快捷方式,两者都会提供正确答案。

卡尔

SoundPimp.com

于 2012-01-31T12:25:20.247 回答