Read Program Data Files

Learn how to read program data files if you run the programs locally.

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.

  1. In LetterPanel.java, change the initial value of the instance variable IMAGENAME to ../WoodTile.jpg.
  2. In the try block of initPanel(), add code to create an InputStream object called input, initialized by getting the letter panel’s class and then getting the resource as a stream using IMAGENAME. Use JPanel's getClass() method. Use Class's getResourceAsStream() method, with IMAGENAME as the parameter value. Import InputStream from java.io.
  3. Change the code that reads from the file to now read from the input and put the results in the image. Use ImageIO's read() 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.