Read Program Data Files
Learn how to read program data files if you run the programs locally.
We'll cover the following
When you run the games of this course locally, you would put the program code into a JAR file and keep all the required data files in the same folder as that JAR file. This is necessary so the program can find the data file if it must make changes to it. However, files that will not be changed could be placed in the JAR file, thus ensuring they’re kept with the JAR file. The Word Builder program must be able to make changes to the high scores and window settings files, but it will never need to make changes to the dictionary or the wood tile image. Therefore the dictionary and wood tile images could be placed in the JAR file with the program.
Read the files from an input stream
A program must use an input stream instead of a file reader to read a file from a JAR file. Read the file from its new location, using an input stream.
- In
LetterPanel.java
, change the initial value of the instance variableIMAGENAME
to../WoodTile.jpg
. - In the try block of
initPanel()
, add code to create anInputStream
object calledinput
, initialized by getting the letter panel’s class and then getting the resource as a stream usingIMAGENAME
. UseJPanel
'sgetClass()
method. UseClass
'sgetResourceAsStream()
method, withIMAGENAME
as the parameter value. ImportInputStream
fromjava.io
. - Change the code that reads from the file to now read from the input and put the results in the image. Use
ImageIO
'sread()
method.
...
protected static final Color BROWN = new Color(49, 22, 3);
private static final String IMAGENAME = "______________";
...
private void initPanel() {
if (image==null) {
try {
_____________ input = getClass().getResourceAsStream(_____________);
image = ImageIO.read(__________);
}
catch(IOException e) {
...
Get hands-on with 1200+ tech skills courses.