Let's get started with a program that reads a file!
Open Eclipse
Right-Click on your edu.buffalostate.cis425.fa10.exercises.src package
Choose: File -> New -> file
In the Name: textbox type: teams
Click: Finish
Copy the teams.txt File (txt) code (below)
Paste that code into your new teams.txt file in the editor
Right-Click on your edu.buffalostate.cis425.fa10.exercises.assignments package
Choose: File -> New -> class
In the Name: textbox type: ReadFile
Click: Finish
Copy the ReadFile.java Template (Java) code (below)
Paste that code into your new ReadFile class in the editor
Change both occurrences of put-your-username-here
Replace blank on line after the: for (String item : teams) {
line with: String[] strParts = item.split( ", " );
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.
*
/**
*
* @authorput-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