31-Files-Crash-Course

31-Files-Crash-Course - CS106A Handout 31 May 9th, 2011...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS106A Handout 31 Spring 2011 May 9 th , 2011 Files: Crash Course FileReader and BufferedReader [example code courtesy of Eric Roberts] Reading data from files is one of the more confusing aspects of Java programming—not because the idea of reading data from a file is conceptually difficult, but because Java makes it more difficult than those just learning to program would like it to be. Conceptually, you can think of the characters in a file as one long, persistent string, with the one limitation that the characters of that string must be read and processed in sequence. /** * File: ReverseFile.java * ---------------------- * This program reverses the lines in a file by reading them into an * ArrayList, converting the ArrayList into a string array, and then * printing the lines of the array in reverse order. */ import acm.program.*; import acm.util.*; import java.io.*; import java.util.*; /** This program reverses the lines in a file */ public class ReverseFile extends ConsoleProgram { public void run() { println("This program reverses the lines in a file."); BufferedReader rd = openInputFile("Enter input file: "); String[] lines = readLineArray(rd); for (int i = lines.length - 1; i >= 0; i--) { println(lines[i]); } } /** * Requests the name of an input file from the user and then opens
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

31-Files-Crash-Course - CS106A Handout 31 May 9th, 2011...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online