Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 File I/O (Input and Output)

2 Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files are more permanent than things stored in variables in programs.

3 Say we have a file called “poem.dat” on disk in some folder. Mares eat oats And does eat oats And little lambs eat ivy.

4 File input Recall how we performed input: Recall how we performed input: Scanner in = new Scanner( System.in ); What is the source of the input? What is the source of the input?

5 File input Instead of this: Scanner in = new Scanner( System.in ); We’ll use: Scanner in = new Scanner( new FileInputStream("data.txt") );

6 File input import java.io.FileInputStream; import java.util.Scanner; class MyIO { public static void main ( String args[] ) throws Exception { public static void main ( String args[] ) throws Exception { Scanner in = new Scanner( new FileInputStream("out.txt") ); Scanner in = new Scanner( new FileInputStream("out.txt") ); //… //… in.close(); in.close(); }}

7 Revisiting the Scanner class String next ( ) String next ( ) Finds and returns the next complete token (i.e., typically “words” separated by whitespace) from this scanner. Finds and returns the next complete token (i.e., typically “words” separated by whitespace) from this scanner. boolean nextBoolean ( ) boolean nextBoolean ( ) Scans the next token of the input into a boolean value and returns that value. Scans the next token of the input into a boolean value and 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 that was skipped. Advances this scanner past the current line and returns the input that was skipped.

8 Additional Scanner class methods String next ( ) String next ( ) Finds and returns the next complete token (i.e., typically “words” separated by whitespace) from this scanner. Finds and returns the next complete token (i.e., typically “words” separated by whitespace) from this scanner. boolean nextBoolean ( ) boolean nextBoolean ( ) Scans the next token of the input into a boolean value and returns that value. Scans the next token of the input into a boolean value and 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. boolean hasNext ( ) boolean hasNext ( ) Returns true if this scanner has another token in its input. boolean hasNextBoolean ( ) boolean hasNextBoolean ( ) Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false". boolean hasNextDouble ( ) boolean hasNextDouble ( ) Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method.

9 Additional Scanner class methods 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 that was skipped. Advances this scanner past the current line and returns the input that was skipped. boolean hasNextFloat ( ) boolean hasNextFloat ( ) Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. boolean hasNextInt ( ) boolean hasNextInt ( ) Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. boolean hasNextLine ( ) boolean hasNextLine ( ) Returns true if there is another line in the input of this scanner.

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

11 Ex. Output contents of file to screen/window. //open the input file Scanner in = new Scanner( new FileInputStream("poem.dat") ); //read one line from the input file 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 if (in.hasNextLine()) { String s = in.nextLine(); String s = in.nextLine(); System.out.println( s ); System.out.println( s );}…in.close();

12 Ex. Output contents of file to screen/window. //open the input file Scanner in = new Scanner( new FileInputStream("poem.dat") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); System.out.println( s ); }in.close();

13 Ex. Output contents of file to screen/window. //open the input file Scanner in = new Scanner( new FileInputStream("poem.dat") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); System.out.println( s ); }in.close(); So when reading from a file, we always need some end-of- file (EOF) test.

14 Ex. Output contents of file to screen/window. //open the input file Scanner in = new Scanner( System.in ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); System.out.println( s ); }in.close(); When reading from the keyboard under Windows, we can indicate EOF by pressing ctrl-Z followed by Enter.

15 Reading Input from a Text File Using Scanner (Part 1 of 4) 10-15Copyright © 2008 Pearson Addison-Wesley. All rights reserved

16 Reading Input from a Text File Using Scanner (Part 2 of 4) 10-16Copyright © 2008 Pearson Addison-Wesley. All rights reserved

17 Reading Input from a Text File Using Scanner (Part 3 of 4) 10-17Copyright © 2008 Pearson Addison-Wesley. All rights reserved

18 Reading Input from a Text File Using Scanner (Part 4 of 4) 10-18Copyright © 2008 Pearson Addison-Wesley. All rights reserved

19 WRITING TO FILES

20 File output If we look at the definition of Java’s System class, we see that System.out is of type PrintStream. If we look at the definition of Java’s System class, we see that System.out is of type PrintStream. To write to a file, we will use FileOutputStream and PrintWriter. To write to a file, we will use FileOutputStream and PrintWriter.

21 File output To write to a file, we will use FileOutputStream and PrintWriter. To write to a file, we will use FileOutputStream and PrintWriter. import java.io.FileOutputStream; import java.io.PrintWriter; 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" ); }}

22 Writing to a file (file output) //create a new, empty output file PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") ); //write something to the output file out.println( "hello fred." ); out.println( "and ethel." ); //close is required for files. // if we forget, the file will be created but it will be empty! out.close();

23 Writing to a file (file output) //create a new, empty output file PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") ); //write something to the output file out.println( "hello fred." ); out.println( "and ethel." ); //close is required for files. // if we forget, the file will be created but it will be empty! 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.

24 Writing to a file (file output) //create a new, empty output file PrintWriter out = new PrintWriter( new FileOutputStream("out.txt“, true) ); //write something to the output file out.println( "hello fred." ); out.println( "and ethel." ); //close is required for files. // if we forget, the file will be created but it will be empty! 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.

25 Writing to a file (file output) //create a new, empty output file PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") ); //write something to the output file out.println( "hello fred." ); out.println( "and ethel." ); //close is required for files. // if we forget, the file will be created but it will be empty! 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.”

26 Checking for the End of a Text File with hasNextLine (Part 1 of 4) 10-26Copyright © 2008 Pearson Addison-Wesley. All rights reserved

27 Checking for the End of a Text File with hasNextLine (Part 2 of 4) 10-27Copyright © 2008 Pearson Addison-Wesley. All rights reserved

28 Checking for the End of a Text File with hasNextLine (Part 3 of 4) 10-28Copyright © 2008 Pearson Addison-Wesley. All rights reserved

29 Checking for the End of a Text File with hasNextLine (Part 4 of 4) 10-29Copyright © 2008 Pearson Addison-Wesley. All rights reserved

30 Checking for the End of a Text File with hasNextInt (Part 1 of 2) 10-30Copyright © 2008 Pearson Addison-Wesley. All rights reserved

31 Checking for the End of a Text File with hasNextInt (Part 2 of 2) 10-31Copyright © 2008 Pearson Addison-Wesley. All rights reserved

32 MAKING A COPY OF A FILE

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

34 Copy one file to another //declare vars & open input and output files Scanner in = new Scanner( new FileInputStream("poem.dat") ); PrintWriter out = new PrintWriter( new FileOutputStream("poem-copy.dat") ); //loop and copy all lines while (in.hasNextLine()) { String s = in.nextLine();//read a line from input out.println( s );//write a line to output }out.close();in.close(); Input file Output file

35 CREATING A SECRET CODE

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

37 Creating a secret code (algorithmic) steps: (algorithmic) steps: 1. What should I call my program (class)? 2. Declare variables. 3. Repeat these steps: 1. Read in a line. 2. Encode a line. 3. Write the encoded line. 4. Finish up.

38 Creating a secret code What is my secret code? How do I encode things? What is my secret code? How do I encode things? Consult Hollywood! Consult Hollywood! “2001” movie “2001” movie Computer called HAL. Computer called HAL. What was HAL really? What was HAL really?

39 Creating a secret code What is my secret code? How do I encode things? What is my secret code? How do I encode things? Consult Hollywood! Consult Hollywood! “2001” movie “2001” movie Computer called HAL. Computer called HAL. What was HAL really? What was HAL really? “HAL” stands for “IBM” – they subtracted 1 from each character. “HAL” stands for “IBM” – they subtracted 1 from each character. We’ll adopt the same technique and make ‘B’ into ‘A’ … We’ll adopt the same technique and make ‘B’ into ‘A’ …

40 Encoding //ch below is a char (a character) char enc = ch; //no change by default //encode the characters if (ch=='a')enc = 'z'; else if (ch=='b')enc = 'a'; else if (ch=='c')enc = 'b'; … else if (ch=='z')enc = 'y';

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

42 //ch below is a char (a character) char enc = ch; //no change by default //encode the characters switch (ch) { case 'a':enc = 'z';break; case 'b':enc = 'a';break; … case 'z':enc = 'y';break; }

43 //ch below is a char (a character) char enc = ch; //no change by default //encode the characters switch (ch) { case 'a':enc = 'z';break; case 'b':enc = 'a';break; … case 'z':enc = 'y';break; } Switch expressions must always evaluate to integers. So how/why does this work?

44 ASCII = American Standard Code for Information Interchange The characters are assigned numbers (integers). The characters are assigned numbers (integers). So we can use them in a switch. So we can use them in a switch. We can also add, subtract, multiply, and divide them! We can also add, subtract, multiply, and divide them!

45 Given that, how can we make this less cumbersome? //ch below is a char (a character) char enc = ch; //default = same //encode the characters if (ch=='a')enc = 'z'; else if (ch=='b')enc = 'a'; else if (ch=='c')enc = 'b'; … //ch below is a char (a character) char enc = ch; //default = same //encode the characters switch (ch) { case 'a':enc = 'z'; break; case 'b':enc = 'a'; break;…}

46 char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged }

47 char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged } How about uppercase letters?

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

49 Casts if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged } cast = convert from other types (int) to this type (char). The result of this expression is an int.

50 Other useful casts. float f = (float)0.3; int i = (int)12.6; Causes truncation. What if I wanted to round? Causes truncation. What if I wanted to round?

51 Casts and rounding double d = 0.9; int i1 = (int) d; int i2 = (int) (d+0.5);

52 Back to our original problem: How can we use this to encode our diary? char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//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.

53 Recall: Output contents of file to screen/window. //open the input file Scanner in = new Scanner( new FileInputStream("diary.txt") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); //perform encoding … //output encoded line System.out.println( s ); }in.close();

54 //open the input file Scanner in = new Scanner( new FileInputStream("diary.txt") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); //perform encoding char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged } //output encoded line System.out.println( s ); }in.close(); How can we get ch from s?

55 //open the input file Scanner in = new Scanner( new FileInputStream("diary.txt") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); char ch = s.charAt( 0 ); //perform encoding char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged } //output encoded line System.out.println( s ); }in.close(); How can we get all of the chars from s?

56 //open the input file Scanner in = new Scanner( new FileInputStream("diary.txt") ); //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); for (int i=0; i<s.length(); i++) { char ch = s.charAt( i ); //perform encoding char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged }} System.out.println( s ); //output encoded line } Now we need to create an output string of encoded chars.

57 //read & write one line at a time while ( in.hasNextLine() ) { String s = in.nextLine(); String outLine = ""; for (int i=0; i<s.length(); i++) { char ch = s.charAt( i ); //perform encoding char enc; if (ch=='a') { enc = 'z'; } else if (ch>'a' && ch 'a' && ch<='z') { enc = (char)(ch-1); } else { enc = ch;//unchanged } outLine = outLine + enc; } System.out.println( outLine ); //output encoded line } We created an output string of encoded chars. Finally, we need to write out the encoded information to another file.

58 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; 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 'a' && ch<='z') { enc = (char)(ch-1); enc = (char)(ch-1); } else if (ch=='A') { //handle uppercase letters enc = 'Z'; } else if (ch>'A' && ch 'A' && ch<='Z') { enc = (char)(ch-1); } else { enc = ch; //unchanged enc = ch; //unchanged } outLine = outLine + enc; outLine = outLine + enc; } out.println( outLine ); //output encoded line out.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!

59 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; class EncodeUseFunction { //encode a given character for our secret code static char encode ( char before ) { char after; if (before=='a') { after = 'z'; } else if (before>'a' && before 'A' && before 'a' && before 'A' && before<='Z') { after = (char)(before-1); } else { after = before; //unchanged } return after; } public static void main ( String args[] ) throws Exception { Scanner in = new Scanner( new FileInputStream("diary.txt") ); PrintWriter out = new PrintWriter( new FileOutputStream("out.txt") ); while ( in.hasNextLine() ) { String s = in.nextLine(); String outLine = ""; System.out.println( "read: " + s ); for (int i=0; i<s.length(); i++) { char ch = s.charAt( i ); //perform encoding outLine = outLine + encode(ch); } out.println( outLine ); //output encoded line } out.close(); in.close(); } }

60 TYPES OF FILES

61 Types of files Text Text only contains lines of ASCII text only contains lines of ASCII text can be viewed with text editors such as notepad can be viewed with text editors such as notepad easier to work with but less compact easier to work with but less compact used in this course used in this course Binary Binary very compact but you have to be privy to the format very compact but you have to be privy to the format cannot be viewed with text editors cannot be viewed with text editors not used in this course not used in this course

62 ANOTHER PROBLEM FOR DISCUSSION

63 Problem for discussion You did a survey. You have a file containing numbers (integers) from a survey. Valid responses are in the range [1..10]. You did a survey. You have a file containing numbers (integers) from a survey. Valid responses are in the range [1..10]. Write a program that reads in these numbers and determines their average. Write a program that reads in these numbers and determines their average. You may assume that the file only contains integers but some responses may not be valid (e.g., 0, -5, or 100). You should not include these values in the average. However, you should print a message like the following: You may assume that the file only contains integers but some responses may not be valid (e.g., 0, -5, or 100). You should not include these values in the average. However, you should print a message like the following: Response number 22 is invalid, -7. Response number 22 is invalid, -7.

64 YET ANOTHER PROBLEM FOR DISCUSSION

65 Yet another problem for discussion You did another survey (of ages of people who voted in the last election). You did another survey (of ages of people who 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 don’t count the min and max? (This is called the trimmed or truncated mean, http://en.wikipedia.org/wiki/Truncated_mean, or the interquartile mean, http://en.wikipedia.org/wiki/Interquartile_mean.) For extra credit, what is the mean voting age if you don’t count the min and max? (This is called the trimmed or truncated mean, http://en.wikipedia.org/wiki/Truncated_mean, or the interquartile mean, http://en.wikipedia.org/wiki/Interquartile_mean.) http://en.wikipedia.org/wiki/Truncated_mean http://en.wikipedia.org/wiki/Interquartile_mean http://en.wikipedia.org/wiki/Truncated_mean http://en.wikipedia.org/wiki/Interquartile_mean


Download ppt "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."

Similar presentations


Ads by Google