Let's get started with a program that reads a file!

  1. Open Eclipse
  2. Right-Click on your edu.buffalostate.cis425.fa10.exercises.src package
  3. Choose: File -> New -> file
  4. In the Name: textbox type: teams
  5. Click: Finish
  6. Copy the teams.txt File (txt) code (below)
  7. Paste that code into your new teams.txt file in the editor
  8. Right-Click on your edu.buffalostate.cis425.fa10.exercises.assignments package
  9. Choose: File -> New -> class
  10. In the Name: textbox type: ReadFile
  11. Click: Finish
  12. Copy the ReadFile.java Template (Java) code (below)
  13. Paste that code into your new ReadFile class in the editor
  14. Change both occurrences of put-your-username-here
  15. Replace blank on line after the:
    for (String item : teams) {
    line with:
      String[] strParts = item.split( ", " );
  16. Click the Run icon

ReadFile.java Template (Java)

package edu.buffalostate.cis425.fa10.exercises..put-your-username-here;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * File: ReadFile.java
 *
 * Create a Java class named ReadFile that reads a txt file and display the contents.
 * 
 * 1) This class contains a main( ) method which uses the files method to read
 *    the contents of a text file into an ArrayList then splits each line and
 *    displays the results.
 *
/**
 *
 * @author put-your-name-here
 *
 */

public class ReadFile {

  public static void main( String args[] ) {
    List<String> teams = new ArrayList<>();
    try { 
      teams = Files.readAllLines(
              Paths.get("src/teams.txt"), Charset.defaultCharset()
              );  
    } catch (IOException | SecurityException e) {
      e.printStackTrace();
    }
    for (String item : teams) {
      ________________________________________
      System.out.println("The " + strParts[0] + " play in " 
       + strParts[1] + ".");
    }
  }
}

teams.txt File (txt)

Blue Jays, Toronto
Red Sox, Boston
Yankees, New York

ReadFile Class Output

The Blue Jays play in Toronto
The Red Sox play in Boston
The Yankees play in New York