65
File I/O (Input and File I/O (Input and Output) Output)

File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Embed Size (px)

Citation preview

Page 1: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File I/O (Input and Output)File I/O (Input and Output)

Page 2: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Why use files?Why use files?

Things stored in files are more permanent Things stored in files are more permanent than things stored in variables in than things stored in variables in programs.programs.

Page 3: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Say we have a file called Say we have a file called “poem.dat” on disk in some folder.“poem.dat” on disk in some folder.

Mares eat oatsMares eat oats

And does eat oatsAnd does eat oats

And little lambs eat ivy.And little lambs eat ivy.

Page 4: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File inputFile input

Recall how we performed input:Recall how we performed input:

Scanner in = new Scanner( System.in );Scanner in = new Scanner( System.in );

What is the source of the input?What is the source of the input?

Page 5: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File inputFile input

Instead of this:Instead of this:

Scanner in = new Scanner( Scanner in = new Scanner( System.inSystem.in ); );

We’ll use:We’ll use:

Scanner in = new Scanner( Scanner in = new Scanner( new FileInputStream("data.txt")new FileInputStream("data.txt") ); );

Page 6: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File inputFile input

import java.io.FileInputStream;import java.io.FileInputStream;

import java.util.Scanner;import java.util.Scanner;

class MyIO {class MyIO {

public static void main ( String args[] ) public static void main ( String args[] ) throws Exceptionthrows Exception { {

Scanner in = new Scanner( Scanner in = new Scanner( new FileInputStream("out.txt")new FileInputStream("out.txt") ); );

//…//…

in.close();in.close();

}}

}}

Page 7: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Revisiting the Scanner classRevisiting the Scanner class String next ( )String next ( )

Finds and returns the next complete token (i.e., typically “words” Finds and returns the next complete token (i.e., typically “words” separated by whitespace) from this scanner.separated by whitespace) from this scanner.

boolean nextBoolean ( )boolean nextBoolean ( ) Scans the next token of the input into a boolean value and Scans the next token of the input into a boolean value and

returns that value.returns that value. double nextDouble ( )double nextDouble ( )

Scans the next token of the input as a double.Scans the next token of the input as a double. float nextFloat ( )float nextFloat ( )

Scans the next token of the input as a float.Scans the next token of the input as a float. int nextInt ( )int nextInt ( )

Scans the next token of the input as an int.Scans the next token of the input as an int. String nextLine ( )String nextLine ( )

Advances this scanner past the current line and returns the input Advances this scanner past the current line and returns the input that was skipped.that was skipped.

Page 8: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Additional Scanner class methodsAdditional Scanner class methods String next ( )String next ( )

Finds and returns the next Finds and returns the next complete token (i.e., typically complete token (i.e., typically “words” separated by whitespace) “words” separated by whitespace) from this scanner.from this scanner.

boolean nextBoolean ( )boolean nextBoolean ( ) Scans the next token of the input Scans the next token of the input

into a boolean value and returns into a boolean value and returns that value.that value.

double nextDouble ( )double nextDouble ( ) Scans the next token of the input Scans the next token of the input

as a double.as a double.

boolean hasNext ( )boolean hasNext ( ) Returns true if this scanner has Returns true if this scanner has

another token in its input.another token in its input.

boolean hasNextBoolean ( )boolean hasNextBoolean ( ) Returns true if the next token in this Returns true if the next token in this

scanner's input can be interpreted as a scanner's input can be interpreted as a boolean value using a case insensitive boolean value using a case insensitive pattern created from the string "true|pattern created from the string "true|false".false".

boolean hasNextDouble ( )boolean hasNextDouble ( ) Returns true if the next token in this Returns true if the next token in this

scanner's input can be interpreted as a scanner's input can be interpreted as a double value using the nextDouble() double value using the nextDouble() method.method.

Page 9: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Additional Scanner class methodsAdditional Scanner class methods float nextFloat ( )float nextFloat ( )

Scans the next token of the input as Scans the next token of the input as a float.a float.

int nextInt ( )int nextInt ( ) Scans the next token of the input as Scans the next token of the input as

an int.an int.

String nextLine ( )String nextLine ( ) Advances this scanner past the Advances this scanner past the

current line and returns the input current line and returns the input that was skipped.that was skipped.

boolean hasNextFloat ( )boolean hasNextFloat ( ) Returns true if the next token in Returns true if the next token in

this scanner's input can be this scanner's input can be interpreted as a float value using interpreted as a float value using the nextFloat() method.the nextFloat() method.

boolean hasNextInt ( )boolean hasNextInt ( ) Returns true if the next token in Returns true if the next token in

this scanner's input can be this scanner's input can be interpreted as an int value in the interpreted as an int value in the default radix using the nextInt() default radix using the nextInt() method.method.

boolean hasNextLine ( )boolean hasNextLine ( ) Returns true if there is another line Returns true if there is another line

in the input of this scanner.in the input of this scanner.

Page 10: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

SHOW THE CONTENTS OF A SHOW THE CONTENTS OF A FILE (IN A WINDOW)FILE (IN A WINDOW)

Page 11: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Ex. Output contents of file to Ex. Output contents of file to screen/window.screen/window.

//open the input file//open the input fileScanner in = new Scanner( new FileInputStream("poem.dat") );Scanner in = new Scanner( new FileInputStream("poem.dat") );

//read one line from the input file//read one line from the input fileif (in.hasNextLine()) {if (in.hasNextLine()) { String s = in.nextLine();String s = in.nextLine(); System.out.println( s );System.out.println( s );}}//read another line from the input file//read another line from the input fileif (in.hasNextLine()) {if (in.hasNextLine()) { String s = in.nextLine();String s = in.nextLine(); System.out.println( s );System.out.println( s );}}……in.close();in.close();

Page 12: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Ex. Output contents of file to Ex. Output contents of file to screen/window.screen/window.

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream("poem.dat") );Scanner in = new Scanner( new FileInputStream("poem.dat") );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

Page 13: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Ex. Output contents of file to Ex. Output contents of file to screen/window.screen/window.

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream("poem.dat") );Scanner in = new Scanner( new FileInputStream("poem.dat") );

//read & write one line at a time//read & write one line at a time

while ( while ( in.hasNextLine()in.hasNextLine() ) { ) {

String s = in.nextLine();String s = in.nextLine();

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

So when reading from a file, we always need some end-of-file (EOF) test.

Page 14: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Ex. Output contents of file to Ex. Output contents of file to screen/window.screen/window.

//open the input file//open the input file

Scanner in = new Scanner( Scanner in = new Scanner( System.inSystem.in ); );

//read & write one line at a time//read & write one line at a time

while ( while ( in.hasNextLine()in.hasNextLine() ) { ) {

String s = in.nextLine();String s = in.nextLine();

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

When reading from the keyboard under Windows, we can indicate EOF by pressing ctrl-Z followed by Enter.

Page 15: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Reading Input from a Text File Using Reading Input from a Text File Using ScannerScanner (Part 1 of 4)(Part 1 of 4)

10-10-1515 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 16: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Reading Input from a Text File Using Reading Input from a Text File Using ScannerScanner (Part 2 of 4)(Part 2 of 4)

10-10-1616 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 17: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Reading Input from a Text File Using Reading Input from a Text File Using ScannerScanner (Part 3 of 4)(Part 3 of 4)

10-10-1717 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 18: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Reading Input from a Text File Using Reading Input from a Text File Using ScannerScanner (Part 4 of 4)(Part 4 of 4)

10-10-1818 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 19: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

WRITING TO FILESWRITING TO FILES

Page 20: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File outputFile output

If we look at the definition of Java’s If we look at the definition of Java’s System class, we see that System.out is System class, we see that System.out is of type PrintStream.of type PrintStream.

To write to a file, we will use To write to a file, we will use FileOutputStream and PrintWriter.FileOutputStream and PrintWriter.

Page 21: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

File outputFile output To write to a file, we will use FileOutputStream and To write to a file, we will use FileOutputStream and

PrintWriter.PrintWriter.import java.io.FileOutputStream;import java.io.FileOutputStream;

import java.io.PrintWriter;import java.io.PrintWriter;

class MyIO {class MyIO {

public static void main ( String args[] ) throws Exception {public static void main ( String args[] ) throws Exception {

System.out.println( "begin writing to a file" );System.out.println( "begin writing to a file" );

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

out.println( "hello fred." );out.println( "hello fred." );

out.println( "and ethel." );out.println( "and ethel." );

//close is required for files. if we forget, the file will be created//close is required for files. if we forget, the file will be created

// but it will be empty!// but it will be empty!

out.close();out.close();

System.out.println( "done writing to a file" );System.out.println( "done writing to a file" );

}}

}}

Page 22: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Writing to a file (file output)Writing to a file (file output)

//create a //create a new, emptynew, empty output file output file

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

//write something to the output file//write something to the output file

out.println( "hello fred." );out.println( "hello fred." );

out.println( "and ethel." );out.println( "and ethel." );

//close is required for files.//close is required for files.

// if we forget, the file will be created but it will be empty!// if we forget, the file will be created but it will be empty!

out.close();out.close();

Page 23: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Writing to a file (file output)Writing to a file (file output)

//create a //create a new, emptynew, empty output file output file

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

//write something to the output file//write something to the output file

out.println( "hello fred." );out.println( "hello fred." );

out.println( "and ethel." );out.println( "and ethel." );

//close is required for files.//close is required for files.

// if we forget, the file will be created but it will be empty!// if we forget, the file will be created but it will be empty!

out.close();out.close();

If the file already exists, it will be erased and a new, empty output file will be created. The old contents, if any, will be lost.

Page 24: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Writing to a file (file output)Writing to a file (file output)

//create a //create a new, emptynew, empty output file output file

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt“, PrintWriter out = new PrintWriter( new FileOutputStream("out.txt“, truetrue) );) );

//write something to the output file//write something to the output file

out.println( "hello fred." );out.println( "hello fred." );

out.println( "and ethel." );out.println( "and ethel." );

//close is required for files.//close is required for files.

// if we forget, the file will be created but it will be empty!// if we forget, the file will be created but it will be empty!

out.close();out.close();

This will cause new information to be added at the end. The original contents will not be lost.

This is called append mode.

The other, default mode is called overwrite.

Page 25: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Writing to a file (file output)Writing to a file (file output)

//create a new, empty output file//create a new, empty output file

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

//write something to the output file//write something to the output file

out.println( "hello fred." );out.println( "hello fred." );

out.println( "and ethel." );out.println( "and ethel." );

//close is required for files.//close is required for files.

// if we forget, the file will be created but it will be empty!// if we forget, the file will be created but it will be empty!

out.close();out.close(); Close is required because this is buffered I/O: “Rather than physically writing every instance of output data as soon as possible, the data is saved in a temporary location, known as a buffer; when enough data is accumulated in this temporary location, it is physically written to the file. This can add to efficiency, since physical writes to a file can be slow.”

Page 26: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextLinehasNextLine (Part 1 of 4) (Part 1 of 4)

10-10-2626 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 27: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextLinehasNextLine (Part 2 of 4) (Part 2 of 4)

10-10-2727 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 28: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextLinehasNextLine (Part 3 of 4) (Part 3 of 4)

10-10-2828 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 29: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextLinehasNextLine (Part 4 of 4) (Part 4 of 4)

10-10-2929 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 30: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextInthasNextInt (Part 1 of 2) (Part 1 of 2)

10-10-3030 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 31: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Checking for the End of a Text File with Checking for the End of a Text File with hasNextInthasNextInt (Part 2 of 2) (Part 2 of 2)

10-10-3131 Copyright © 2008 Pearson Copyright © 2008 Pearson Addison-Wesley. All rights Addison-Wesley. All rights

reservedreserved

Page 32: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

MAKING A COPY OF A FILEMAKING A COPY OF A FILE

Page 33: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

So how do I write a program So how do I write a program to copy one file to another to copy one file to another

file?file?

Page 34: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Copy one file to anotherCopy one file to another//declare vars & open input and output files//declare vars & open input and output filesScanner in = new Scanner( new FileInputStream("poem.dat") );Scanner in = new Scanner( new FileInputStream("poem.dat") );PrintWriter out = new PrintWriter(PrintWriter out = new PrintWriter(

new FileOutputStream("poem-copy.dat") );new FileOutputStream("poem-copy.dat") );

//loop and copy all lines//loop and copy all lineswhile (in.hasNextLine()) {while (in.hasNextLine()) {

String s = in.nextLine();String s = in.nextLine(); //read a line from input//read a line from inputout.println( s );out.println( s ); //write a line to output//write a line to output

}}

out.close();out.close();in.close();in.close();

Input file

Output file

Page 35: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

CREATING A SECRET CODECREATING A SECRET CODE

Page 36: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Creating a secret codeCreating a secret code

Problem: I keep my diary in a text file Problem: I keep my diary in a text file called “diary.txt”. I think my little brother is called “diary.txt”. I think my little brother is reading my diary. I’d like to encode it so reading my diary. I’d like to encode it so he can’t read it.he can’t read it.

Page 37: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Creating a secret codeCreating a secret code

(algorithmic) steps:(algorithmic) steps:1.1. What should I call my program (class)?What should I call my program (class)?

2.2. Declare variables.Declare variables.

3.3. Repeat these steps:Repeat these steps:1.1. Read in a line.Read in a line.

2.2. Encode a line.Encode a line.

3.3. Write the encoded line.Write the encoded line.

4.4. Finish up.Finish up.

Page 38: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Creating a secret codeCreating a secret code

What is my secret code? How do I What is my secret code? How do I encode things?encode things?

Consult Hollywood!Consult Hollywood! ““2001” movie2001” movieComputer called HAL.Computer called HAL.What was HAL really?What was HAL really?

Page 39: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Creating a secret codeCreating a secret code

What is my secret code? How do I encode What is my secret code? How do I encode things?things?

Consult Hollywood!Consult Hollywood! ““2001” movie2001” movieComputer called HAL.Computer called HAL.What was HAL really?What was HAL really?

““HAL” stands for “IBM” – they subtracted 1 from HAL” stands for “IBM” – they subtracted 1 from each character.each character.

We’ll adopt the same technique and make ‘B’ into ‘A’ We’ll adopt the same technique and make ‘B’ into ‘A’ ……

Page 40: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

EncodingEncoding

//ch below is a char (a character)//ch below is a char (a character)char enc = ch; //no change by defaultchar enc = ch; //no change by default

//encode the characters//encode the charactersif (ch=='a')if (ch=='a') enc = 'z';enc = 'z';else if (ch=='b')else if (ch=='b') enc = 'a';enc = 'a';else if (ch=='c')else if (ch=='c') enc = 'b';enc = 'b';……else if (ch=='z')else if (ch=='z') enc = 'y';enc = 'y';

Page 41: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Another way to encodeAnother way to encode

What statement (other than ‘if’) did we see What statement (other than ‘if’) did we see recently that can also be used for recently that can also be used for encoding?encoding?

Page 42: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//ch below is a char (a character)//ch below is a char (a character)char enc = ch; //no change by defaultchar enc = ch; //no change by default

//encode the characters//encode the charactersswitch (ch) {switch (ch) {

case 'a':case 'a': enc = 'z';enc = 'z'; break;break;case 'b':case 'b': enc = 'a';enc = 'a'; break;break;……case 'z':case 'z': enc = 'y';enc = 'y'; break;break;

}}

Page 43: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//ch below is a char (a character)//ch below is a char (a character)char enc = ch; //no change by defaultchar enc = ch; //no change by default

//encode the characters//encode the charactersswitch (ch) {switch (ch) {

case 'a':case 'a': enc = 'z';enc = 'z'; break;break;case 'b':case 'b': enc = 'a';enc = 'a'; break;break;……case 'z':case 'z': enc = 'y';enc = 'y'; break;break;

}}

Switch expressions must always evaluate to integers. So how/why does this work?

Page 44: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

ASCII = American Standard Code ASCII = American Standard Code for Information Interchangefor Information Interchange

The characters are assigned numbers The characters are assigned numbers (integers).(integers).

So we can use them in a switch.So we can use them in a switch.

We can also add, subtract, multiply, and We can also add, subtract, multiply, and divide them!divide them!

Page 45: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Given that, how can we make this Given that, how can we make this less cumbersome?less cumbersome?

//ch below is a char (a character)//ch below is a char (a character)

char enc = ch; //default = samechar enc = ch; //default = same

//encode the characters//encode the charactersif (ch=='a')if (ch=='a') enc = enc =

'z';'z';else if (ch=='b')else if (ch=='b') enc = enc =

'a';'a';else if (ch=='c')else if (ch=='c') enc = enc =

'b';'b';……

//ch below is a char (a character)//ch below is a char (a character)

char enc = ch; //default = samechar enc = ch; //default = same

//encode the characters//encode the charactersswitch (ch) {switch (ch) {

case 'a':case 'a': enc = 'z';enc = 'z';break;break;

case 'b':case 'b': enc = 'a';enc = 'a';break;break;

……}}

Page 46: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

Page 47: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

How about uppercase letters?

Page 48: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else if (ch=='A') { //handle uppercase letters} else if (ch=='A') { //handle uppercase letters

enc = 'Z';enc = 'Z';

} else if (ch>'A' && ch<='Z') {} else if (ch>'A' && ch<='Z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

Page 49: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

CastsCasts

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}} cast = convert from other types (int) to this type (char).

The result of this expression is an int.

Page 50: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Other useful casts.Other useful casts.

float f = (float)0.3;float f = (float)0.3;

int i = (int)12.6;int i = (int)12.6;Causes truncation. What if I wanted to Causes truncation. What if I wanted to

round?round?

Page 51: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Casts and roundingCasts and rounding

double d = 0.9;double d = 0.9;

int i1 = (int) d;int i1 = (int) d;

int i2 = (int) (d+0.5);int i2 = (int) (d+0.5);

Page 52: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Back to our original problem:Back to our original problem:How can we use this to encode our How can we use this to encode our

diary?diary?

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

Algorithm:•What should I call my program (class)?•Declare variables.•Repeat these steps:

•Read in a line.•Encode a line.•Write the encoded line.

•Finish up.

Page 53: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Recall: Output contents of file to Recall: Output contents of file to screen/window.screen/window.

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream(Scanner in = new Scanner( new FileInputStream("diary.txt""diary.txt") );) );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

//perform encoding//perform encoding

……

//output encoded line//output encoded line

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

Page 54: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream(Scanner in = new Scanner( new FileInputStream("diary.txt""diary.txt") );) );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

//perform encoding//perform encoding

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

//output encoded line//output encoded line

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

How can we get ch from s?

Page 55: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream("diary.txt") );Scanner in = new Scanner( new FileInputStream("diary.txt") );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

char ch = s.charAt( 0 );char ch = s.charAt( 0 );

//perform encoding//perform encoding

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

//output encoded line//output encoded line

System.out.println( s );System.out.println( s );

}}

in.close();in.close();

How can we get all of the chars from s?

Page 56: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream("diary.txt") );Scanner in = new Scanner( new FileInputStream("diary.txt") );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

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

char ch = s.charAt( char ch = s.charAt( ii ); );

//perform encoding//perform encoding

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

}}

System.out.println( s ); //output encoded lineSystem.out.println( s ); //output encoded line

}}

Now we need to create an output string of encoded chars.

Page 57: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

String outLine = "";String outLine = "";

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

char ch = s.charAt( i );char ch = s.charAt( i );

//perform encoding//perform encoding

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else {} else {

enc = ch;enc = ch; //unchanged//unchanged

}}

outLine = outLine + enc;outLine = outLine + enc;

}}

System.out.println( System.out.println( outLineoutLine ); //output encoded line ); //output encoded line

}}

We created an output string of encoded chars.

Finally, we need to write out the encoded information to another file.

Page 58: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

import java.io.FileInputStream;import java.io.FileInputStream;

import java.io.FileOutputStream;import java.io.FileOutputStream;

import java.io.PrintWriter;import java.io.PrintWriter;

import java.util.Scanner;import java.util.Scanner;

class Encode {class Encode {

public static void main ( String args[] ) throws Exception {public static void main ( String args[] ) throws Exception {

//open the input file//open the input file

Scanner in = new Scanner( new FileInputStream("diary.txt") );Scanner in = new Scanner( new FileInputStream("diary.txt") );

//open the output file//open the output file

PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

//read & write one line at a time//read & write one line at a time

while ( in.hasNextLine() ) {while ( in.hasNextLine() ) {

String s = in.nextLine();String s = in.nextLine();

String outLine = "";String outLine = "";

System.out.println( "read: " + s );System.out.println( "read: " + s );

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

char ch = s.charAt( i );char ch = s.charAt( i );

//perform encoding//perform encoding

char enc;char enc;

if (ch=='a') {if (ch=='a') {

enc = 'z';enc = 'z';

} else if (ch>'a' && ch<='z') {} else if (ch>'a' && ch<='z') {

enc = (char)(ch-1);enc = (char)(ch-1);

} else if (ch=='A') { //handle uppercase letters} else if (ch=='A') { //handle uppercase letters enc = 'Z'; enc = 'Z'; } else if (ch>'A' && ch<='Z') { } else if (ch>'A' && ch<='Z') { enc = (char)(ch-1); enc = (char)(ch-1); } else { } else {

enc = ch; //unchangedenc = ch; //unchanged

}}

outLine = outLine + enc;outLine = outLine + enc;

}}

out.println( outLine ); //output encoded lineout.println( outLine ); //output encoded line

}}

out.close();out.close();

in.close();in.close();

}}

}}

Here’s the complete program that writes the encoded information to another file.

Don’t forget that you need a decoder program too!

Page 59: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

import java.io.FileInputStream;import java.io.FileInputStream;

import java.io.FileOutputStream;import java.io.FileOutputStream;

import java.io.PrintWriter;import java.io.PrintWriter;

import java.util.Scanner;import java.util.Scanner;

class EncodeUseFunction {class EncodeUseFunction { //encode a given character for our secret code//encode a given character for our secret code static char encode ( char before ) {static char encode ( char before ) { char after; char after; if (before=='a') { if (before=='a') { after = 'z'; after = 'z'; } else if (before>'a' && before<='z') { } else if (before>'a' && before<='z') { after = (char)(before-1); after = (char)(before-1); } else if (before=='A') { //handle uppercase letters } else if (before=='A') { //handle uppercase letters after = 'Z'; after = 'Z'; } else if (before>'A' && before<='Z') { } else if (before>'A' && before<='Z') { after = (char)(before-1); after = (char)(before-1); } else { } else { after = before; //unchanged after = before; //unchanged } } return after; return after; } } public static void main ( String args[] ) throws Exception { public static void main ( String args[] ) throws Exception {

Scanner in = new Scanner( new FileInputStream("diary.txt") ); Scanner in = new Scanner( new FileInputStream("diary.txt") ); PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") ); PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") );

while ( in.hasNextLine() ) { while ( in.hasNextLine() ) { String s = in.nextLine(); String s = in.nextLine(); String outLine = ""; String outLine = ""; System.out.println( "read: " + s ); System.out.println( "read: " + s ); for (int i=0; i<s.length(); i++) { for (int i=0; i<s.length(); i++) { char ch = s.charAt( i ); char ch = s.charAt( i ); //perform encoding //perform encoding

outLine = outLine + outLine = outLine + encode(ch);encode(ch); } } out.println( outLine ); //output encoded line out.println( outLine ); //output encoded line } } out.close(); out.close(); in.close(); in.close(); } }}}

Page 60: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

TYPES OF FILESTYPES OF FILES

Page 61: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Types of filesTypes of files

TextText only contains lines of ASCII textonly contains lines of ASCII text can be viewed with text editors such as notepadcan be viewed with text editors such as notepad easier to work with but less compacteasier to work with but less compact used in this courseused in this course

BinaryBinary very compact but you have to be privy to the formatvery compact but you have to be privy to the format cannot be viewed with text editorscannot be viewed with text editors not used in this coursenot used in this course

Page 62: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

ANOTHER PROBLEM FOR ANOTHER PROBLEM FOR DISCUSSIONDISCUSSION

Page 63: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Problem for discussionProblem for discussion

You did a survey. You have a file containing You did a survey. You have a file containing numbers (integers) from a survey. Valid responses numbers (integers) from a survey. Valid responses are in the range [1..10].are in the range [1..10].

Write a program that reads in these numbers and Write a program that reads in these numbers and determines their average.determines their average.

You may assume that the file only contains integers You may assume that the file only contains integers but some responses may not be valid (e.g., 0, -5, or but some responses may not be valid (e.g., 0, -5, or 100). You should not include these values in the 100). You should not include these values in the average. However, you should print a message like average. However, you should print a message like the following:the following: Response number 22 is invalid, -7.Response number 22 is invalid, -7.

Page 64: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

YET ANOTHER PROBLEM FOR YET ANOTHER PROBLEM FOR DISCUSSIONDISCUSSION

Page 65: File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files

Yet another problem for Yet another problem for discussiondiscussion

You did another survey (of ages of people who You did another survey (of ages of people who voted in the last election).voted in the last election).

You keep the ages in a file.You keep the ages in a file. What is the min, max, and mean voting age?What is the min, max, and mean voting age? For extra credit, what is the mean voting age if you For extra credit, what is the mean voting age if you

don’t count the min and max? (This is called the don’t count the min and max? (This is called the trimmed or truncated mean, trimmed or truncated mean, http://en.wikipedia.org/wiki/Truncated_mean, or , or the interquartile mean, the interquartile mean, http://en.wikipedia.org/wiki/Interquartile_mean.).)