programing

응용 프로그램의 경로 가져 오기

nasanasas 2020. 10. 10. 10:08
반응형

응용 프로그램의 경로 가져 오기


최근에 Java에서 응용 프로그램의 디렉토리를 얻는 방법을 검색했습니다. 마침내 답을 찾았지만 그러한 일반적인 용어를 검색하는 것이 쉽지 않기 때문에 놀랍도록 오래 필요했습니다. 여러 언어로 이것을 달성하는 방법 목록을 컴파일하는 것이 좋은 생각이라고 생각합니다.

아이디어가 마음에 들지 않으면 자유롭게 업 / 다운 투표하고 마음에 들면 기여해주세요 .

설명:

실행 파일이 포함디렉토리현재 작업 디렉토리 ( pwdUnix에서 제공) 사이에는 미세한 차이 가 있습니다 . 나는 원래 전자에 관심이 있었지만 후자를 결정하는 방법도 게시 할 수 있습니다 (어떤 것을 의미하는지 명확히 함).


에서 자바 호출은

System.getProperty("user.dir")

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

현재 작업 디렉토리를 반환합니다.

호출

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

현재 클래스를 포함하는 JAR 파일의 경로를 반환하거나 파일 시스템에서 직접 실행중인 경우 현재 클래스를 생성 한 CLASSPATH 요소 (경로)를 반환합니다.

예:

  1. 신청서는 다음 위치에 있습니다.

     C:\MyJar.jar
    
  2. 셸 (cmd.exe)과 cdC : \ test \ subdirectory를 엽니 다 .

  3. 명령을 사용하여 응용 프로그램을 시작합니다 java -jar C:\MyJar.jar.

  4. 처음 두 번의 호출은 'C : \ test \ subdirectory'를 반환합니다. 세 번째 호출은 'C : \ MyJar.jar'을 반환합니다.

JAR 파일이 아닌 파일 시스템에서 실행할 때 결과는 생성 된 클래스 파일의 루트 경로가됩니다. 예를 들어

c:\eclipse\workspaces\YourProject\bin\

경로에는 생성 된 클래스 파일의 패키지 디렉토리가 포함되지 않습니다.

.jar 파일 이름없이 애플리케이션 디렉토리를 가져 오거나 파일 시스템에서 직접 실행하는 경우 (예 : 디버깅시) 클래스 파일에 대한 해당 경로를 가져 오는 완전한 예제 :

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

if (applicationDir.endsWith(".jar"))
{
    applicationDir = new File(applicationDir).getParent();
}
// else we already have the correct answer

에서 .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

에서 윈도우 의 WinAPI를 기능을 사용 하여 GetModuleFileName ()를 . 모듈 핸들에 NULL을 전달하여 현재 모듈의 경로를 가져옵니다.


파이썬

path = os.path.dirname(__file__)

현재 모듈의 경로를 가져옵니다.


Objective-C Cocoa (Mac OS X, iPhone 사양에 대해 잘 모릅니다) :

NSString * applicationPath = [[NSBundle mainBundle] bundlePath];

Java 에서는 애플리케이션의 경로를 찾는 두 가지 방법이 있습니다. 하나는 다음을 사용하는 것입니다 System.getProperty.

System.getProperty("user.dir");

또 다른 가능성은 다음을 사용하는 것입니다 java.io.File.

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

또 다른 가능성은 반사를 사용합니다.

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

VB6에서는 App.Path속성을 사용하여 응용 프로그램 경로를 가져올 수 있습니다 .

\응용 프로그램이 드라이브의 루트에있는 경우 뒤에는 EXCEPT 가 없습니다 .

IDE에서 :

?App.Path
C:\Program Files\Microsoft Visual Studio\VB98

.Net 에서는 다음을 사용할 수 있습니다.

System.IO.Directory.GetCurrentDirectory

응용 프로그램의 현재 작업 디렉토리를 얻으려면 특히 VB.NET에서 다음을 사용할 수 있습니다.

My.Application.Info.DirectoryPath

exe의 디렉토리를 가져옵니다.


델파이

Windows 애플리케이션에서 :

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

콘솔 애플리케이션에서 :

언어에 관계없이 첫 번째 명령 줄 매개 변수는 완전한 실행 파일 이름입니다.

Unit System;
path := ExtractFilePath(ParamStr(0));

Libc
In * nix 유형 환경 (Windows의 Cygwin) :

  #include <unistd.h>

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

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

   char *get_current_dir_name(void);

맨 페이지 참조


유닉스

유닉스에서는 환경 변수를 사용하여 시작된 실행 파일의 경로를 찾을 수 있습니다. 반드시 절대 경로 일 필요 없으므로 현재 작업 디렉토리 (쉘 pwd:) 및 / 또는 PATH 변수를 환경의 0 번째 요소 값과 결합해야합니다.

예를 들어 실행 파일이 심볼릭 링크를 통해 호출 될 수 있고 환경 변수에 대해 초기 링크 만 사용되기 때문에 값은 유닉스에서 제한됩니다. 일반적으로 유닉스의 응용 프로그램은 흥미로운 일 (예 : 리소스로드)에 이것을 사용하면 그다지 강력하지 않습니다. 유닉스에서는 /etc리소스 위치가 지정된 구성 파일과 같이 사물에 대해 하드 코딩 된 위치를 사용하는 것이 일반적 입니다.


에서 배쉬 는 'PWD'명령은 현재 작업 디렉토리를 반환합니다.


에서 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).
?>

에서 안드로이드

getApplicationInfo().dataDir;

SD 카드를 얻으려면

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

후자는 특정 유형의 파일 (오디오 / 영화 등)을 저장하는 데 사용됩니다. 환경 클래스에 이러한 문자열에 대한 상수가 있습니다.

Basically, for anything to with app use ApplicationInfo class and for anything to do with data in SD card / External Directory using Environment class.

Docs : ApplicationInfo , Environment


In Tcl

Path of current script:

set path [info script]

Tcl shell path:

set path [info nameofexecutable]

If you need the directory of any of these, do:

set dir [file dirname $path]

Get current (working) directory:

set dir [pwd]

in Ruby, the following snippet returns the path of the current source file:

path = File.dirname(__FILE__)

In CFML there are two functions for accessing the path of a script:

getBaseTemplatePath()
getCurrentTemplatePath()

Calling getBaseTemplatePath returns the path of the 'base' script - i.e. the one that was requested by the web server.
Calling getCurrentTemplatePath returns the path of the current script - i.e. the one that is currently executing.

Both paths are absolute and contain the full directory+filename of the script.

To determine just the directory, use the function getDirectoryFromPath( ... ) on the results.

So, to determine the directory location of an application, you could do:

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

Inside of the onApplicationStart event for your Application.cfc



To determine the path where the app server running your CFML engine is at, you can access shell commands with cfexecute, so (bearing in mind above discussions on pwd/etc) you can do:

Unix:

<cfexecute name="pwd"/>

for Windows, create a pwd.bat containing text @cd, then:

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

(Use the variable attribute of cfexecute to store the value instead of outputting to screen.)


In cmd (the Microsoft command line shell)

You can get the name of the script with %* (may be relative to pwd)

This gets directory of script:

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

If you find any bugs, which you will. Then please fix or comment.


I released https://github.com/gpakosz/whereami which solves the problem in C and gives you:

  • the path to the current executable
  • the path to the current module (differs from path to executable when calling from a shared library).

It uses GetModuleFileNameW on Windows, parses /proc/self/maps on Linux and Android and uses _NSGetExecutablePath or dladdr on Mac and iOS.


Java:

On all systems (Windows, Linux, Mac OS X) works for me only this:

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;
}

Note to answer "20 above regarding Mac OSX only: If a JAR executable is transformed to an "app" via the OSX JAR BUNDLER, then the getClass().getProtectionDomain().getCodeSource().getLocation(); will NOT return the current directory of the app, but will add the internal directory structure of the app to the response. This internal structure of an app is /theCurrentFolderWhereTheAppReside/Contents/Resources/Java/yourfile

Perhaps this is a little bug in Java. Anyway, one must use method one or two to get the correct answer, and both will deliver the correct answer even if the app is started e.g. via a shortcut located in a different folder or on the desktop.

carl

SoundPimp.com

참고URL : https://stackoverflow.com/questions/218061/get-the-applications-path

반응형