java - java中如何获取执行目录路径

标签 java

<分区>

我制作了一个纯 Java 应用程序,它告诉我给定目录中的文件数量。现在我使用以下代码设置当前目录:

`File f = new File(".");`

之后,我用它的 jar 文件制作了一个安装程序并将其安装在我的 Windows 8 中,然后我将它添加到 Windows 右键单击​​下拉菜单(上下文菜单)中。当我从上下文菜单启动它时,它总是告诉我它实际安装的目录中的文件数,但是我想知道我正在执行它的目录中的文件数。

所以请帮助我。我是这个领域的新手,我不想让你在当前目录和当前执行目录中混淆我。所以我写了这么久,希望能用非常简单的语言得到一个清晰的答案。

谢谢

最佳答案

正如 Jarrod Roberson 在 his answer here 中所说的那样:

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

示例:获取执行路径

import java.util.*;
import java.lang.*;

public class GetExecutionPath
{
  public static void main(String args[]) {
    try{
      String executionPath = System.getProperty("user.dir");
      System.out.print("Executing at =>"+executionPath.replace("\\", "/"));
    }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
    }
  }
}

上面的输出是这样的

C:\javaexamples>javac GetExecutionPath.jav

C:\javaexamples>java GetExecutionPath
Executing at =>C:/javaexamples

关于java - java中如何获取执行目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939556/

相关文章:

java - 即使应用程序被销毁也保持 'logged in'

java - 通过 Google DataFlow Transformer 查询关系数据库

java - 如何编写一个聊天程序,就像 gtalk 或 yahoo 一样

java - 为什么通过jdbc连接mysql时不能静态加载sql Driver类?

java - 弹出组合框并使用键盘快捷键选择

java - 收到致命警报 : handshake_failure

java - 为什么Eclipse不在 "Generate Delegate Methods"重构中添加@Override注解?

java - 尝试使用 Spring Boot 通过 Oauth2 和 Strava 验证 Web 应用程序时出错

java - Struts2 Hibernate(返回一个列表,导致 hibernate 从所有关系中获取数据)

java - Weblogic集群环境下如何设置远程调试?