简体   繁体   English

在Eclipse和Java中执行期间的不同相对文件路径

[英]Different relative file path during execution in Eclipse and Java

I have implemented a Java class that handles files of .txt-Format by relative paths. 我实现了一个Java类,该类通过相对路径处理.txt格式的文件。 It works all well during execution in Eclipse. 在Eclipse中执行期间,一切正常。 But if I'm executing the (unchanged) compiled file in the Java JRE outside of Eclipse, I'm getting a java.io.FileNotFoundException. 但是,如果我要在Eclipse之外的Java JRE中执行(未更改的)编译文件,则会得到java.io.FileNotFoundException。

I implemented new File(".").getCanonicalPath() and found the source of my problem: 我实现了new File(".").getCanonicalPath()并找到了问题的根源:

Executed in Eclipse I get returned: C:\\Users\\xy\\git\\Project\\Project 在Eclipse中执行后,我返回了: C:\\Users\\xy\\git\\Project\\Project

Executed in Java 8 JRE I get returned: C:\\Users\\xy\\git\\Project\\Project\\bin 在Java 8 JRE中执行后,我返回了: C:\\Users\\xy\\git\\Project\\Project\\bin

I thought of a workaround, but handling two different code versions for development and deployment seems an unnecessary source of errors to me. 我想到了一种解决方法,但是对我来说,处理两个不同的代码版本以进行开发和部署似乎是不必要的错误来源。

So my question is how to fix the problem. 所以我的问题是如何解决问题。 I would prefer a hint how to reconfigure Eclipse. 我希望获得有关如何重新配置​​Eclipse的提示。

Thanks in advance Threx 在此先感谢Threx

There are many ways: 有很多方法:

  1. do not put your text file in the /bin, point to another more static path 不要将文本文件放在/ bin中,指向另一个更静态的路径
  2. load the file into classpath 将文件加载到类路径
  3. use combination of System.getProperties("user.dir") and if-else statement 结合使用System.getProperties(“ user.dir”)和if-else语句
  4. use maven, ref: Maven add properties file to jar file 使用Maven,参考: Maven将属性文件添加到jar文件

The solution lies in adapting the configuration of Eclipse. 解决方案在于调整Eclipse的配置。

Under Run | 在运行中 Run Configurations… | 运行配置…| slide Arguments there is the entry "Working directory" . slide参数存在条目“工作目录”。 By default it is set to ${workspace_loc: ProjectName}. 默认情况下,它设置为$ {workspace_loc:ProjectName}。 After changing it to ${workspace_loc:ProjectName/bin} the java.io.FileNotFoundException-warnings are gone and everything works as intended. 将其更改为$ {workspace_loc:ProjectName / bin}后,java.io.FileNotFoundException-警告消失了,一切都按预期进行。

Now Eclipse and the JRE outside of Eclipse work with the same path and no more redundant code with workarounds is needed. 现在,Eclipse和Eclipse外部的JRE使用相同的路径工作,不需要更多的带有变通方法的冗余代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM