首页 > 图灵资讯 > 技术篇>正文

Java 获取当前exe路径

2023-11-05 17:42:57

Java 获取当前 exe 路径

在 Java 我们可以用一些方法来获得现在 exe 文件路径。在本文中,我们将介绍一些常用的方法,并提供相应的代码示例。

1. 使用 System 类的 getProperty() 方法

Java 中的 System 类提供了 getProperty() 该方法可获得系统属性。我们可以使用这种方法来获得当前的系统属性。 exe 文件路径。具体步骤如下:

  1. 使用 System.getProperty("java.class.path") 获取当前类别路径。
  2. 使用 File 类的 getAbsoluteFile() 该方法获得当前类别的绝对路径。
  3. 使用 getParent() 获取当前父路径的方法。

以下是使用该方法获取当前信息的方法 exe 路径代码示例:

import java.io.File;public class GetCurrentExePath {    public static void main(String[] args) {        String classPath = System.getProperty("java.class.path");        File currentClassFile = new File(classPath).getAbsoluteFile();        String currentExePath = currentClassFile.getParent();        System.out.println("当前 exe 路径:" + currentExePath);    }}
2. 使用 CodeSource 类的 getLocation() 方法

Java 中的 CodeSource 类提供了 getLocation() 该方法可以获得代码源的位置。我们可以使用这种方法来获得当前的位置 exe 文件路径。具体步骤如下:

  1. 使用 GetCurrentExePath.class.getProtectionDomain().getCodeSource().getLocation() 获取当前类的代码源位置。
  2. 使用 File 类的 getAbsolutePath() 该方法获得当前类别的绝对路径。
  3. 使用 getParent() 获取当前父路径的方法。

以下是使用该方法获取当前信息的方法 exe 路径代码示例:

import java.io.File;import java.net.URL;public class GetCurrentExePath {    public static void main(String[] args) {        URL location = GetCurrentExePath.class.getProtectionDomain().getCodeSource().getLocation();        File currentClassFile;        try {            currentClassFile = new File(location.toURI());            String currentExePath = currentClassFile.getParent();            System.out.println("当前 exe 路径:" + currentExePath);        } catch (Exception e) {            e.printStackTrace();        }    }}
序列图

下面是使用 mermaid 目前已获得语法绘制 exe 路径序列图:

sequenceDiagram    participant JavaCode    participant SystemClass    participant FileClass    participant GetCurrentExePathClass    JavaCode->>+SystemClass: getProperty("java.class.path")    SystemClass-->>-JavaCode: classPath    JavaCode->>+FileClass: new File(classPath)    FileClass-->>-JavaCode: currentClassFile    JavaCode->>+currentClassFile: getAbsoluteFile()    currentClassFile-->>-JavaCode: currentClassFile    JavaCode->>+currentClassFile: getParent()    currentClassFile-->>-JavaCode: currentExePath    JavaCode->>+SystemClass: println("当前 exe 路径:" + currentExePath)
关系图

下面是使用 mermaid 目前已获得语法绘制 exe 路径关系图:

erDiagram    File ||--|| GetCurrentExePath : contains    GetCurrentExePath }|--|| System : uses

通过以上方法,我们可以很容易地获得当前的方法 exe 文件路径。希望这篇文章能理解你 Java 中获取当前 exe 路径的方法有帮助!

上一篇 Java 获取redis中的key和value方法
下一篇 Java 计算两个时间戳相差几个小时

文章素材均来源于网络,如有侵权,请联系管理员删除。