0

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);


}
Cipher
  • 3
  • 1
  • 1
    Possible duplicate of [How to read a file from jar in Java?](https://stackoverflow.com/questions/3369794/how-to-read-a-file-from-jar-in-java) – dnault Sep 22 '19 at 21:14

1 Answers1

1

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);
        ...
multicatch
  • 192
  • 4