【问题标题】:How to get path to package in Eclipse (Java)如何在 Eclipse (Java) 中获取包的路径
【发布时间】:2017-05-12 09:34:42
【问题描述】:

我目前正在阅读 Java 中的 txt 文件,该文件位于带有扫描仪对象的包中。

为了接收文件位置,我使用了一种快速而肮脏的方法:

File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";  
  • 有更好的方法吗?

我很想改进我的代码。

问候 J

【问题讨论】:

标签: java eclipse


【解决方案1】:

使用网址

URL resource = getClass().getResource("/path/to/text/file.txt");  

作为路径,由于您的文本文件位于包内,因此请使用包结构。例如,假设您的文件(myfile.txt)在里面

com.myproject.files 

包,你的路径应该是

"/com/myproject/files/myfile.txt"

(注意前面的斜线。这是必要的)

现在您可以使用 URL 创建文件

new File(resource.getFile());

“resource.getFile()”也返回文件的绝对路径。

希望对你有帮助

【讨论】:

    【解决方案2】:

    获取当前目录路径

    String currentDirPath = System.getProperty("user.dir");
    
    String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
    

    用户主目录

    String homePath = System.getProperty("user.home");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多