简体   繁体   中英

How to correctly reference a text file after exporting jar project

Making a small hangman game just for fun and to experiment more with IO. Original Solution was as the code shows which works in the IDE (Using Netbeans). Issue is that when i export it as a Jar file, it can't find the file I'm referencing. How do I correctly read from an external file once it's exported?

public HangmanGame(){
    File file = new File("src\\hangman\\words");
    try{
    Scanner fileScan = new Scanner(file);

    int number = (int)(Math.random()*260);
    for(double i=0; i<260; i++){
        if(i == number){
            word = fileScan.nextLine();
            fileScan.close();
            break;
        }else{
            fileScan.nextLine();
        }

    }
    }catch(FileNotFoundException e){
        System.out.println(e.getMessage());

    }
    System.out.println(word);


}

Place your file inside of project "resources" - it will get packed into a jar. Then you need to read it from inside the jar, not the filesystem - see this thread for reference and this answer if you need a fallback method for running the project in IDE and directly from jar.

tl;dr: Your code should look more like this

    try {
        InputStream in = getClass().getResourceAsStream("words");
        Scanner fileScan = new Scanner(in);
        ...

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