Issue
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
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
Solution
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));
Answered By - Lê Hoàng Dững