






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Class: LAB:Comp Program & Prob Solv; Subject: Computer Science; University: Wellesley College; Term: Fall 2007;
Typology: Study notes
1 / 11
This page cannot be seen from the preview
Don't miss anything!







Tuesday, November 27, 2007
File I/0 21-
A file is an abstraction for storing information (text, images, music, etc.) on a computer.
Today we will explore how to read information from (Input) and write information to (Output) files in Java. Input/Output is often abbreviated I/0.
We will focus on files with textual information, but the techniques we’ll learn generalize to any kind of information.
File I/0 21-
Writing to Standard Output
System.out.println writes a string to the Java console (standard output file).
0 1 2 3 4
String []
args
“rocks” “3.141”
“Sam I am!”
java WriteToConsole CS 111 rocks 3.141 “Sam I am!”
CS
111
rocks
Sam I am!
File I/0 21-
Writing to a File
import java.io.*;
public class WriteToFile {
public static void main (String [ ] args) throws IOException { String filename = args[0]; BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (int i = 1; i < args.length; i++) { writer.write(args[i]); writer.newLine(); // Same as writer.write("\n"); } writer.close(); } }
java WriteToFile out.txt CS 111 rocks 3.141 “Sam I am!” CS 111 rocks
Sam I am!
out.txt
FileWriter, BufferedWriter, and IOException live in the java.io package
File operations can generate IOExceptions
Finish any output to file. File is not guaranteed to contain all output until closed.
Idiom for creating a file writer. If file doesn’t exist, creates it. If file exists, overwrites it.
Append string to end of file.
File I/0 21-
Reading From a File
import java.io.*;
// Display the contents of a file, line by line public class DisplayFile {
public static void main (String [ ] args) throws IOException { String filename = args[0]; BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); // read the first line in file while (line != null) { System.out.println(line); line = reader.readLine(); // read next line from the file. } reader.close(); // Tidy up } }
java DisplayFile out.txt CS 111 rocks
Sam I am!
rocks
Sam I am!
out.txt
Idiom for creating a file reader. Throws an IOException if file doesn’t exist.
readLine() returns next line from file as a string (without trailing newline character). It returns null if there are no more lines in the file.
File I/0 21-
Transforming a File
java UpperCaseFile cat4.txt cat4Upper.txt
Let’s write a Java application that uppercases each line of a file (using the String toUpperCase() method).
input filename output filename
File I/0 21-
UppercaseFile
import java.io.;*
// Application that writes an output file that uppercases each line // of an input file public class UpperCaseFile {
public static void main (String [ ] args) throws IOException { String infile = args[0]; String outfile = args[1]; BufferedReader reader = new BufferedReader(new FileReader(infile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outfile)); String line = reader.readLine(); // read the first line in file while (line != null) { // readLine() returns null when reaches end of file writer.write(line.toUpperCase()); writer.newLine(); line = reader.readLine(); // read next line from the file. } reader.close(); // Tidy up writer.close(); } }
File I/0 21-
Sorting the Lines of a File
java SortLines animals.txt animalsSorted.txt
Let’s write a Java application that sorts the lines of a file.
Assume we can use the following method from the CS111 StringArray class:
input filename output filename
File I/0 21-
stringArrayToFile() is Easy
// Writes each element of a string array to a line of a file named filename. public static void stringArrayToFile(String[] strings, String filename) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (int i = 0; i < strings.length; i++) { writer.write(strings[i]); writer.newLine(); } writer.close(); }
File I/0 21-
fileToLineArray() is Trickier
// Returns a string array containing the lines of the file named filename. public static String[] fileToLineArray(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename));
int numLines = ???
String [] lines = new String[numLines]; for (int i = 0; i < numLines; i++) { lines[i] = reader.readLine(); } reader.close(); return lines; }
How do we know the number of lines?
File I/0 21-
fileToLineArray(): Solution 1
// Returns a string array containing the lines of the file named filename. public static String[] fileToLineArray(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); String header = reader.readLine(); // Read integer header in first line int numLines = Integer.parseInt(header); String [] lines = new String[numLines]; for (int i = 0; i < numLines; i++) { lines[i] = reader.readLine(); } reader.close(); return lines; }
Idea: Assume the first line of every file is an integer specifying the number of lines in the rest of the file.
This is sensible for specialized files (like the image files in PS9), but not all files will have this format.
File I/0 21-
fileToLineArray(): Solution 2
// Returns a string array containing the lines of the file named filename. public static String[] fileToLineArray(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); int numLines = countLines(filename); // Count the lines in the file. String [] lines = new String[numLines]; for (int i = 0; i < numLines; i++) { lines[i] = reader.readLine(); } reader.close(); return lines; }
Idea: Count the lines in a file first in a separate pass over the file. This works for any file, but processes all the lines twice.
// Returns the number of lines in a file. public static int countLines (String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); int count = 0; String line = reader.readLine(); while (line != null) { count++; line = reader.readLine(); } reader.close(); return count; }
File I/0 21-
SortWords: Just A Modification To Sort Lines
public static void main (String [ ] args) throws IOException { String infile = args[0]; String outfile = args[1]; String[] lines = fileToLineArray(infile); String[] words = lineArrayToWordArray(lines); StringArray.sort(words); stringArrayToFile(words, outfile); }
input file
array of lines from file
array of words from file
sorted array of words from file
output file
File I/0 21-
How to Write lineArrayToWordArray?
public static String[] lineArrayToWordArray(String[] lines) { // Since we don't know how many words there will be, // we create a StringList of all the words and convert // this back to an array. StringList wordList = StringList.empty(); for (int i = 0; i < lines.length; i++) { // Splits line into “words” separated by space, “ ”. String[] words_in_line = lines[i].split(" "); wordList = StringListOps.append(wordList, arrayToList(words_in_line)); } return listToArray(wordList); }
Hint: Use split(“ ”) from the String class to break lines into “words” (character sequences separated by a space).
File I/0 21-
Reading Input from the Java Console
The Java console (e.g., the Dr. Java Interaction Pane) can be viewed as a special kind of file (known as the standard input/output file ). We already know how to write to standard output using System.out.println. We can read from it as well by creating a reader for it using this idiom: new BufferedReader(new InputStreamReader(System.in));
Here’s an example of interacting with the InteractiveUpperCase application defined on the next slide:
java InteractiveUpperCase Type a line to convert to upper case (or quit to exit)>
Type a line to convert to upper case (or quit to exit)>
Type a line to convert to upper case (or quit to exit)>
This is a test; it is only a test.
another example
quit
File I/0 21-
InteractiveUpperCase Application
import java.io.*; // Application that interactively prompts the user for a string, // which is then displayed in upper case form. public class InteractiveUpperCase {
public static void main (String [ ] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Type a line to convert to upper case (or quit to exit)> "); String line = reader.readLine(); while (! line.equals("quit")) { System.out.println(line.toUpperCase()); System.out.println("Type a line to convert to upper case (or quit to exit)> "); line = reader.readLine(); } reader.close(); } }