Lecture Slides on Input and Output - Computer Programming | CS 111, Study notes of Computer Science

Material Type: Notes; Class: LAB:Comp Program & Prob Solv; Subject: Computer Science; University: Wellesley College; Term: Fall 2007;

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-r4a
koofers-user-r4a 🇺🇸

10 documents

1 / 11

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS111 Computer Programming
Department of Computer Science
Wellesley College
File Input/Output (I/0)
Tuesday, November 27, 2007
File I/0 21-2
What is File I/O?
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.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Lecture Slides on Input and Output - Computer Programming | CS 111 and more Study notes Computer Science in PDF only on Docsity!

CS111 Computer Programming

Department of Computer Science

Wellesley College

File Input/Output (I/0)

Tuesday, November 27, 2007

File I/0 21-

What is File I/O?

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).

public class WriteToConsole {

public static void main (String [ ] args) {

for (int i = 0; i < args.length; i++) {

System.out.println(args[i]);

0 1 2 3 4

String []

args

“CS”

“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!

CS

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

The sun did not shine.

It was too wet to play.

So we sat in the house

All that cold, cold, wet day.

cat4.txt

THE SUN DID NOT SHINE.

IT WAS TOO WET TO PLAY.

SO WE SAT IN THE HOUSE

ALL THAT COLD, COLD, WET DAY.

cat4Upper.txt

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

elephant

siamese cat

zebra

aardvark

great white shark

dingo

animals.txt

aardvark

dingo

elephant

great white shark

siamese cat

zebra

animalsSorted.txt

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:

public static sort (String [] strings);

// Modifies strings so that its elements are in dictionary order.

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; }

elephant

siamese cat

zebra

aardvark

great white shark

dingo

animalsWithHeader.txt

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); }

fileToLineArray

lineArrayToWordArray

input file

array of lines from file

array of words from file

StringArray.sort

stringArrayToFile

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)>

THIS IS A TEST; IT IS ONLY A TEST.

Type a line to convert to upper case (or quit to exit)>

ANOTHER EXAMPLE

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(); } }