简体   繁体   中英

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.

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.

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.

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)

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 .

Say its relative path is 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.

If you place it in your package folder you need the relative path to it.

Taking as example this structure

  • src
    • main
      • java
        • com
          • example
            • Main.java
            • configuration.txt

You would access it

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

even if you access it from Main.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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