The Coder's Handbook

Reading Files

The code examples shown on this page are also available on Replit. Fork a copy and experiment.

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.

  • You need to create a File object which is given to the Scanner

  • The Scanner treats the File the same way it would handle console input

  • Loop once for each element in the file and assign each input to the array

  • Print the output to the console to show that it works

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.


  • Create your 2D Array, File, and Scanner objects.

  • Outer loop reads in each row of data as a String

    • Inner loop breaks up each row into individual characters

      • Assign each element of your grid a single character

  • Used a nested loop to iterate over the array

    • Print each element to the console, adding a space for clarity

    • Instead of printing "." this code prints a " "

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.


  • Create your ArrayList, File, and Scanner objects.

  • Keep looping as long as there is more information to read

    • Add the next quote to our list

  • Select a random quote

    • Output a random quote.

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