The Coder's Handbook   

Reading Files

FILES AND EXCEPTIONS

Using Files

Often you'll be dealing with a lot of data in a program, and it isn't a good idea to hardcode everything into a variable.  You also might not want to ask the user for information.  Instead, you can add a file to your project that contains the data you'd like to reference.


To do this, you'll need to create a File Object and then use the Scanner class to get input from it.  This works a lot like getting input from the console.

Exceptions


Working with files is especially error-prone.  Even if your code is right... what if the file was moved by the user?  Or an address is invalid.  Because of this, they will throw an Exception when things go wrong.  This means it's required that you handle or throw the exception.

A SIMPLE EXAMPLE
1D Array of Integers

Summary

This is a basic example of reading a file: a single list of numbers.

Example #1 - Numbers

try

{

   // Initialize variables

   int[] numbers = new int[7];

   File dataFile = new File("data.txt");

   Scanner scan = new Scanner(dataFile);

      

   // Read in the grid pattern in the file

   for(int i = 0; i < numbers.length; i++) 

   {

      numbers[i] = scan.nextInt();

   }

   scan.close();


   // Print out the numbers

   for(int i = 0; i < numbers.length; i++) 

   {

       System.out.println(numbers[i]);   // Print each element

   } 

}

catch(FileNotFoundException e)

{

    System.out.println("Cannot find file!");

}

 
data.txt

5 8 34 129 42 852 3

 
output

5

8

34

129

42

852

3

READING A GRID OF CHARACTERS
2D Array of Chars

Summary


This is an example of how we might want to read in a simple map.  Imagine each char represents a terrain or unit in a game.  For instance, "#" might be a wall while "." is a normal space that allows movement.


Example #2 - Map
Code:

try

{

   // Initialize variables

   final char ROWS = 10;

   final char COLS = 10;

   char[][] grid = new char[ROWS][COLS];

   File mapFile = new File("map.txt");

   Scanner scan = new Scanner(mapFile);

      

   // Read in the grid pattern in the file

   for(int i = 0; i < ROWS; i++)   

   {

      String row = scan.nextLine();

      for(int j = 0; j < COLS; j++)      

      {

        grid[i][j] = row.charAt(j);

      }

   }

   

   scan.close();


   // Print out the map

   for(int i = 0; i < ROWS; i++)  

   {

      for(int j = 0; j < COLS; j++) 

      {

          if(grid[i][j] == '.'

          {  

            System.out.print("  "); // Display a space instead

          }

          else 

          {

            System.out.print(grid[i][j] + " ");   // Print each element

          } 

       }

       System.out.println();

   }


}

catch(FileNotFoundException e)

{

    System.out.println("Cannot find file!");

}

 
map.txt

##########

#P.......#

#...#....#

#...###.##

#.!......#

#......!.#

##.###...#

#....#...#

#.$..#...#

##########

 
output

# # # # # # # # # #

# P               #

#       #         #

#       # # #   # #

#   !             # 

#             !   # 

# #   # # #       # 

#         #       #

#   $     #       #

# # # # # # # # # #

A DYNAMIC LIST OF QUOTES
ArrayList of Strings

Summary


This program simply stores a bunch of quotes in a text file which we can read.  It demonstrates how you can use a file to read an indefinite number of information and store it in a dynamically sized array list.


Example #3 - Quotes
Code:

try

{

   // Initialize variables

   ArrayList<String> quotes = new ArrayList<String>();

   File quoteFile = new File("quote.txt");

   Scanner scan = new Scanner(quoteFile);

      

   // Read in the grid pattern in the file

   while(scan.hasNextLine())

   {

      quotes.add(scan.nextLine());

   }

   scan.close();


   // Print a random quote

   int r = (int) (Math.random() * quotes.size());

   System.out.println(quotes.get(r));

}

catch(FileNotFoundException e)

{

    System.out.println("Cannot find file!");

}

 
quotes.txt

“It always takes longer than you expect, even when you take into account Hofstadter’s Law.” - Hofstadter’s Law

“Debugging is like being the detective in a crime movie where you are also the murderer” -Filipe Fortes

“Any sufficiently advanced bug is indistinguishable from a feature.” -R. Kulawiec

“What one programmer can do in one month, two programmers can do in two months” - Fred Brooks

 
output

“Any sufficiently advanced bug is indistinguishable from a feature.” -R. Kulawiec

RESOURCES