0

This is my first time writing a small application in javafx, using IntelliJ. The problem I'm having is that, although I've my text file and images in the same namespace as the Controller.java file, when I run the application, I still get the error that files cannot be found.

try (BufferedReader reader = new BufferedReader(new FileReader("bookList.txt")))
{
   //code here...
}
catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

this is for the image

Image image = new  
           Image(getClass().getResourceAsStream("images/book1.jpg"));
ImageView imageView = new ImageView(image);

Here's the structure of the files

enter image description here

After reading some questions/answers, it seems like the issue is related to those resources not being copied to the output path.

In visual studio, all you have to do is right-click the file then chose "Copy to Output Directory: Always | If Newer"

How do I copy text files and/or images to the output path in java/IntelliJ?

Thanks for helping

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 1
    If you're using your `src` folder for resources as well then [mark the `src` folder as a resources content root](https://www.jetbrains.com/help/idea/content-roots.html), in addition to it being a sources content root. If you actually have a separate content root for resources then move your resources there; you can mirror the package structure and at runtime they'll be in the same package. – Slaw May 01 '20 at 06:58
  • 1
    Also, note that `new Image(getClass().getResourceAsStream("images/book1.jpg"))` fails to close the `InputStream` afterwards. – Slaw May 01 '20 at 07:05
  • 1
    Do you use Maven to build your project or something else? – Puce May 01 '20 at 13:51
  • The question https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other has some very detailed information on locating resources (mostly describing .fxml files, but the information mostly applies to any kind of resource files) that may be useful. There are some Maven-specific tricks there to do what you want. – Some Guy Dec 31 '22 at 14:40

1 Answers1

2

If you use the path: right-click on the source file> copy> Path from content Root: The result is:

BufferedReader reader = new BufferedReader(new 
    FileReader("src\\sample\\bookList.txt"))

If you use URL, the URL starts from src, in this case:

Image image = new
            Image(getClass().getResourceAsStream("/sample/images/book1.jpg"));

Ideally, you should use the URL for BufferedReader:

String fileName = "/sample/bookList.txt";
InputStream is = getClass().getResourceAsStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));