简体   繁体   English

Java-netbeans 8.1:无法识别的文件?

[英]Java-netbeans 8.1: Unrecognized file?

so i developed a java application and trying to read the file in, i get error message saying the file configuration.txt doesnt exist. 因此,我开发了一个Java应用程序并尝试读取文件,我得到一条错误消息,提示文件configuration.txt不存在。

here is the file reading code: 这是文件读取代码:

    public static void main(String[] args) throws FileNotFoundException {

    //reading configuration file
    Scanner readConfigurationFile = new Scanner(new File("configuration.txt"));

yes, i do have the imported necessary IO library and utilities included. 是的,我确实包含了导入的必要IO库和实用程序。

i moved the file everywhere (in the package, or in the project folder, or the bin folder, etc..) and kept testing, but it didnt work. 我将文件移动到了所有位置(在程序包中,项目文件夹中或bin文件夹中,等等。)并进行了测试,但没有成功。

the only way it works is when i moved it to the desktop and i put the path of the file on the desktop in the code (so C:\\User\\....\\configuration.txt) 唯一有效的方法是将其移至桌面,然后在代码中将文件的路径放在桌面上(因此C:\\ User \\ .... \\ configuration.txt)

but thats not how i want it, because others have to run it without changing code. 但这不是我想要的,因为其他人必须在不更改代码的情况下运行它。

any suggestions/help? 有什么建议/帮助吗? i have looked everywhere online and tried different methods but they didnt work. 我在网上到处都看过,尝试过不同的方法,但是它们没有用。 and some would complicate my code so i just avoided. 有些会使我的代码复杂化,所以我避免了。

thanks in advance 提前致谢

If your configuration file is intended to live inside the application (it will be deployed inside the jar or war) you should not use it as a File but as a Resource . 如果您的配置文件旨在驻留在应用程序内部(它将部署在jar或war中), 则不应将其用作File而是用作Resource

Say its relative path is org/example/files/configuration.txt (*). 假设其相对路径为org/example/files/configuration.txt (*)。 You can use it that way: 您可以通过以下方式使用它:

InputStream is = getClass().getClassLoader().loadRessourceAsStream(
    "org/example/files/configuration.txt");
Scanner readConfigurationFile = new Scanner(is);

(*) It could be src/main/resources/org/... if you use maven, or src/org/... if you use ant or eclipse notive compiler. (*),这可能是src/main/resources/org/...如果你用maven,或src/org/...如果你使用ant或偏食notive编译器。

If you place it in your package folder you need the relative path to it. 如果将其放在包文件夹中,则需要相对路径。

Taking as example this structure 以这种结构为例

  • src src
    • main 主要
      • java 爪哇
        • com com
          • example
            • Main.java Main.java
            • configuration.txt configuration.txt

You would access it 您将访问它

new File("src/main/java/com/example/configuration.txt");

even if you access it from Main.java 即使您从Main.java访问它

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

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