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

  1. Login to your Repl.It account.
  2. Click on: Languages
  3. In the Popular section choose: Java: A concurrent, class-based, statically typed object-oriented language.
  4. Click the pencil icon next to your repl name.
  5. In the Default name: input box type: ReadFile
  6. Delete all the lines of code provided as an example.
  7. Copy the ReadFile.java Template (Java) code (below)
  8. Paste that code into your new ReadFile class in the editor
  9. Change the @author put-your-username-here
  10. Replace blank on line after the:
    for (String item : teams) {
    line with:
      String[] strParts = item.split( ", " );
  11. Click on the Add File (+) icon.
  12. Name this file: teams.txt
  13. Delete all the lines of code provided as an example.
  14. Copy the GCP_Student.java Template (Java) code (below)
  15. Paste that code into your new GCP_Student class in the editor
  16. Click the Run icon

ReadFile.java Template (Java)

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 Main {

  public static void main( String args[] ) {
    List<String> teams = new ArrayList<>();
    try { 
      teams = Files.readAllLines(
              Paths.get("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