【问题标题】:Opening a text file using relative path with Java (in Eclipse)使用 Java 的相对路径打开文本文件(在 Eclipse 中)
【发布时间】:2014-06-17 11:43:08
【问题描述】:

我尝试使用相对路径打开一个文件,我的文件位于项目的根文件夹中。

BufferedReader reader = new BufferedReader(new FileReader("text.h"));

那没用。

所以我打印了工作目录,但这会将我引导到安装 eclipse 的目录。

 System.out.println(new File(".").getAbsolutePath());

我的项目结构:

Project
       --bin
       --core
           text.h
           --src
              text.h 
              --com
                 --home
                     --core
                         Main.java
                         text.h
       --editor
       --ui
       text.h

我已将文本文件复制到不同位置,在我的项目目录中,我尝试了不同的路径,但都没有奏效。

如果我将文件复制到安装 Eclipse 的目录中,那么我可以使用以下路径读取文件。

BufferedReader reader = new BufferedReader(new FileReader("text.h"));

如何从项目的根文件夹中读取文件?

【问题讨论】:

  • 使用“/”可以访问根文件夹。向我们展示您的项目结构。
  • System.getProperty("user.dir") 可以显示您当前的工作目录。如果该路径低于您的工作目录,那么您可能需要将一些 ../.. 附加到 File 构造函数 arg
  • 如果您不想使用绝对路径,您可以在 Eclipse 工作区中添加一个系统变量来获取值。然后,将项目的根文件夹添加到变量中。如果您需要查找特定的 abs 路径,它不会降低程序的可移植性。
  • @omu_negru System.getProperty("user.dir");和 System.out.println(new File(".").getAbsolutePath());打印相同的路径。

标签: java eclipse relative-path


【解决方案1】:
String workingDir = System.getProperty("user.dir");


BufferedReader reader = new BufferedReader(new FileReader(workingDir+"\text.h"));

workingDir 的值给出了当前工作目录的路径

试试这个可能对你有帮助

【讨论】:

  • workingDir 将我带到安装 eclipse 的目录。
【解决方案2】:
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
System.out.println("URL " + url.toExternalForm());

URL file:/D:/workspace/myproject/bin/

或者当 jar 被点击时:

URL file:jar:/D:/workspace/myproject/bin/myproject.jar!/....

【讨论】:

  • 我不需要在对象上调用 getClass() 函数吗?我试过 URL url = Main.class.getClass().getProtectionDomain().getCodeSource().getLocation(),但我得到了 NullPointerException。
  • MainClass.class.getProtectionDomain()... 当然。 ;) 否则Class.class.
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多