Text File Input Output Outcomes Know the difference

  • Slides: 57
Download presentation
Text File Input & Output

Text File Input & Output

Outcomes § Know the difference between files and streams § Use a Scanner to

Outcomes § Know the difference between files and streams § Use a Scanner to read from a file add “throws” annotations to methods use the has. Next family of methods to read every element in a file § Use a Print. Writer object to write to a file § Know when and why to close file streams how to use autoclose to ensure they get closed § Know how to read an entire text file

Input & Output Streams § System. in and System. out are streams carry information

Input & Output Streams § System. in and System. out are streams carry information from one place to another System. in: from keyboard to program System. out: from program to monitor System. in (kbd) keyboard System. out Program monitor

File Streams § Can get program to read from/write to files connect Scanner to

File Streams § Can get program to read from/write to files connect Scanner to a file instead of System. in use a Print. Writer instead of System. out carry information to/from files fin (Scanner) file. In. txt fout (Print. Writer) myprog. exe file. Out. txt

Possible Program Variables § § String for name of input file File for input

Possible Program Variables § § String for name of input file File for input file information Scanner for reading from file int/double/String/… for data read from file and for values calculated from that input data § String for name of output file § File for output file information § Print. Writer for writing to file

Importing the Required Types § Scanner comes from java. util import java. util. Scanner;

Importing the Required Types § Scanner comes from java. util import java. util. Scanner; § Others come from java. io import java. io. File; import java. io. Print. Writer; import java. io. File. Not. Found. Exception; » we’ll need this last one, too

Text Files § We will only read from text files have. txt extension on

Text Files § We will only read from text files have. txt extension on a Windows system » tho’ Windows may hide it from you! § Text files may contain numbers (numerals) and may contain only numbers 10 15 340 -7 -2 103 3 Numbers. txt Twas brillig and the slithy toves poem. txt

Why Use Files? § Permanence can re-use input; don’t need to copy output can

Why Use Files? § Permanence can re-use input; don’t need to copy output can use output of one program as input to next § Accuracy correct before the program gets it even “invisible” output characters stored § Ease of use large quantities of input hard to type correctly

Program Input § So far – input comes from user/keyboard characters in blue typed

Program Input § So far – input comes from user/keyboard characters in blue typed in by user Enter numbers below, and I'll calculate their average. Enter a negative number to end input. 10 20 30 40 50 60 70 80 90 100 110 125 107 104 77 42 19 91 85 77 23 27 106 88 -1 The average of the 25 numbers you entered is 70. 04

Scanner for Input § We use a Scanner to read from the user psf

Scanner for Input § We use a Scanner to read from the user psf Scanner KBD = new Scanner(System. in); System. in: an object connected to the keyboard kbd: a Scanner connected to System. in Scanners know how to read numbers & Strings int num = KBD. next. Int(); String word = KBD. next(); double x = KBD. next. Double(); String line = KBD. next. Line();

Lots of Input § There may be a LOT of input The average of

Lots of Input § There may be a LOT of input The average of the 600 numbers you entered is 483. 28. hard for user to type it all in correctly prepare it in a file ahead of time » can proof-read file to make sure it’s right copy file contents; paste as input » recall: Reverse 600. java § Can we make that easier? 677 924 528 738 755 411 414 147 739 167 my. Data. txt

Reading Directly from a File § Scanner needs to be told where to get

Reading Directly from a File § Scanner needs to be told where to get input from keyboard Scanner kbd = new Scanner(System. in); from a String line = KBD. next. Line(); Scanner string. Input = new Scanner(line); from a file File the. File = new File("my. Data. txt"); Scanner file. Input = new Scanner(the. File); Remember to import java. io. File;

Reading From a File § Once the Scanner is connected to the file, input

Reading From a File § Once the Scanner is connected to the file, input is just like reading from kbd int num = file. Input. next. Int(); String word = file. Input. next(); double x = file. Input. next. Double(); String line = file. Input. next. Line(); you already know how to do this! the new bit is getting the connection set up

Reading from a File § Don’t ask the user to type in the data!

Reading from a File § Don’t ask the user to type in the data! the data is already in a file the program will read directly from the file asking the user for that data would be confusing Enter numbers below, and I'll calculate their average. Enter a negative number to end input. The average of the 25 numbers you entered is 70. 04

The File Data Type § Import from java. io import java. io. File; §

The File Data Type § Import from java. io import java. io. File; § Represents a file on your computer constructor gives name of file File the. File = new File("my. Data. txt"); NOTE: my. Data. txt should already exist… » it’s a new object representing the file …but it might not » it might actually represent a new file

File Objects vs. Files § File exists in secondary storage on disk, on thumb

File Objects vs. Files § File exists in secondary storage on disk, on thumb drive, … § File object in main memory the. File = new File("my. Data. txt"); does not have file contents! the. File & main memory name: "my. Data. txt" exists: true … 677 924 528 738 755 411 414 147 739 167 my. Data. txt secondary storage

The Scanner § Tell the Scanner to read from the file Scanner file. Input

The Scanner § Tell the Scanner to read from the file Scanner file. Input = new Scanner(the. File); § Problem: File. Not. Found. Exception » must be declared or caught need a try-catch block for this exception » “checked” exception » NOT a Runtime. Exception

Method to Open a File Scanner § Separate from main program logic connect to

Method to Open a File Scanner § Separate from main program logic connect to the file, or die trying! private static Scanner get. Scanner. For(String file. Name) { try { File the. File = new File(file. Name); return new Scanner(the. File); } catch (File. Not. Found. Exception fnf) { System. err. println("Cannot open " + file. Name); System. exit(1); } } Recall that if new Scanner throws an exception, then return does not get executed.

Reading the File Name § Can ask the user for the name of the

Reading the File Name § Can ask the user for the name of the file user gets to choose what file to use a Scanner connected to System. in for input Scanner kbd = new Scanner(System. in); System. out. print("Enter file name: "); file. Name = KBD. next. Line(); Scanner file. Input = get. Scanner. For(file. Name); » program ends if named file doesn’t exist

Requesting Alternatives § Method requests file names until one works private static Scanner get.

Requesting Alternatives § Method requests file names until one works private static Scanner get. Scanner() { while (true) { System. out. print("Enter file name: "); try { return new Scanner(new File(KBD. next. Line())); } catch (File. Not. Found. Exception fnf) { System. out. println("I can't find that file!"); } } }

Limiting Number of Tries § Give up after a certain number of failures replace

Limiting Number of Tries § Give up after a certain number of failures replace while (true) with a counting loop for (int try = 1; try <= MAX_TRIES; ++i) { // same loop body as previous slide } add code after loop to report failure » won’t reach this code unless failed three times System. err. println("Too many fails. Quitting. "); System. exit(1); return null; // necessary to soothe Java

Reading File Contents § Reverse 600 program reads 600 numbers count control: for loop

Reading File Contents § Reverse 600 program reads 600 numbers count control: for loop § Java. Average reads to negative number sentinel control: while loop § Want to read all data in file shouldn’t have to count the number of elements shouldn’t have to add a sentinel value

While The File Has Data § Can ask any Scanner if next thing exists

While The File Has Data § Can ask any Scanner if next thing exists has. Next returns true if there is a next element while (file. Input. has. Next()) { … } use next / next. Int / etc. to get that element could also use has. Next. Int, has. Next. Double, … » has. Next. Int = has. Next and next is an int » has. Next. Double = has. Next and next is a double while (file. Input. has. Next. Int()) { ++count; sum += file. Input. next. Int(); }

Saving All The Data § Don’t read into an array there might be too

Saving All The Data § Don’t read into an array there might be too much data! § Read into a List<Integer> values = new Array. List<>(); while (file. Input. has. Next. Int()) { values. add(file. Input. next. Int()); } can now process data using List operations

One More Thing § Connecting to a file uses system resources system is limited

One More Thing § Connecting to a file uses system resources system is limited in how many files can be open file can’t be edited while program has it open usually not a problem for very small programs » but still, practice freeing up resources » close file input stream as soon as you’re done while (file. Input. has. Next. Int()) { values. add(file. Input. next. Int()); } file. Input. close();

Exercise § Write a program fragment to read a file name from the user,

Exercise § Write a program fragment to read a file name from the user, then report how many words are in that file. if file doesn’t exist, report that instead

Program Output § So far – input goes to the screen characters in black

Program Output § So far – input goes to the screen characters in black printed by program Enter numbers below, and I'll calculate their average. Enter a negative number to end input. 10 20 30 40 50 60 70 80 90 100 110 125 107 104 77 42 19 91 85 77 23 27 106 88 -1 The average of the 25 numbers you entered is 70. 04

Print. Writer for Output § We’ve used System. out for output System. out. print("This

Print. Writer for Output § We’ve used System. out for output System. out. print("This is console output: "); System. out. println(sum); § System. out’s data type is Print. Stream § But Print. Writer is better and it has all the same print methods makes printing to a file easy for us file. Output. print("This is file output: "); file. Output. println(sum);

Connecting to an Output File § Same as for connecting a Scanner File the.

Connecting to an Output File § Same as for connecting a Scanner File the. File = new File(file. Name); Print. Writer file. Output = new Print. Writer(the. File); § Same problem – File. Not. Found. Exception weird, but true! what it really means is: I can’t write to that file! » many reasons for this » usually has to do with permissions

Get The Printer Method § Separate from main program get a Print. Writer or

Get The Printer Method § Separate from main program get a Print. Writer or die trying! private static Print. Writer get. Printer. For(String file. Name) { try { return new Print. Writer(new File(file. Name)); } catch (File. Not. Found. Exception fnf) { System. err. println("Cannot open " + file. Name); System. exit(2); } } We’re using System. exit(1) for failing to open input file. Use a different error code (2) for failing to open output file.

Writing to the File § Send reversed numbers to the file after reading all

Writing to the File § Send reversed numbers to the file after reading all the numbers into a List Print. Writer file. Output = get. Printer. For("reversed. txt"); for (int i = values. size() – 1; i >= 0; --i) { file. Output. println(values. get(i)); } file. Output. close(); don’t forget to close the connection » forget some numbers may be missing! » recall: output buffering

Choosing the Output File § Same options as for input file user can type

Choosing the Output File § Same options as for input file user can type in file name can ask again when File. Not. Found. Exception » remember, that might happen » remember, means can’t write to that file can limit number of chances much, much more!

Re-Writing a File § If you run the program again, the new output replaces

Re-Writing a File § If you run the program again, the new output replaces the old output need to do special stuff to append to file § Old file contents are erased as soon as the Print. Writer connects if you don’t print anything, file still gets erased

Exercise § Write a program fragment to read ten lines from the user and

Exercise § Write a program fragment to read ten lines from the user and save them in a file named my. Lines. txt.

Looking for Files § Net. Beans looks in the project folder Week 09 program

Looking for Files § Net. Beans looks in the project folder Week 09 program looks in Week 09 folder § What if data is somewhere else? can give the program a path to the data include the path as part of the name » use / after each folder name (NOT or : ) Enter the name of the file: data. Folder/my. Data. txt The average of the 25 numbers you entered is 70. 04

Files & Folders § Files exist inside folders src Lab 03 J: Net. Beans

Files & Folders § Files exist inside folders src Lab 03 J: Net. Beans Projects Lab 05 my. Prog. java classes my. Prog. class Lab 05 Data. txt J: Net. Beans ProjectsLab 03srcmy. Prog. java J: Net. Beans ProjectsLab 05 Data. txt

Files & Folders § If you just give the name of the file… my.

Files & Folders § If you just give the name of the file… my. Data. txt § Net. Beans looks in the project folder not the src folder! Looks here… src Lab 03 § But you can specify other folders absolute/relative paths …not there

File Paths § Somewhat system dependent but can always use / to separate folder

File Paths § Somewhat system dependent but can always use / to separate folder names remember to “escape” if inside quote marks § Absolute path J: /Net. Beans Projects/Lab 05 Data. txt § Relative path (from L 03 folder) . . /Lab 05 Data. txt

File Paths § Use / in Strings in your code will work on any

File Paths § Use / in Strings in your code will work on any machine, not just Windows § “. . ” means the folder my folder is in “. . /. . ” means the folder that it’s in » and so on! J: § Put data files in project folder § Use relative paths Lab 03 Net. Beans Project Folder. . /. .

Exercise § Given this directory structure, how would we refer to my. Prog. java

Exercise § Given this directory structure, how would we refer to my. Prog. java from a program in Lab 03? src Lab 03 J: Net. Beans Projects Lab 05 my. Prog. java classes my. Prog. class Lab 05 Data. txt

More File I/O Information § § Not catching the File. Not. Found. Exception Output

More File I/O Information § § Not catching the File. Not. Found. Exception Output buffering Appending to a file The File type and its uses

Not Catching the FNFException § An error message when we try to open a

Not Catching the FNFException § An error message when we try to open a file “… java. io. File. Not. Found. Exception must be caught or declared to be thrown” § FNFExn is not a Runtime. Exceptions are nicer » don’t need to say you’re not catching them you need to catch the FNFException… … or say you’re not going to catch it!

Declaring an Exception § Say you’re not catching it public static void some. Method(String

Declaring an Exception § Say you’re not catching it public static void some. Method(String some. Param) throws File. Not. Found. Exception { » NOTE where it is – before the body’s opening brace § Note: throws instead of throw is a command » tells computer to do something throws is a description » says what this method sometimes does

When to Use a throws Clause § Use throws File. Not. Found. Exception in

When to Use a throws Clause § Use throws File. Not. Found. Exception in any method that opens a file (without catching) any method that calls any method that has that throws clause (and doesn’t catch it) public static void another. Method() throws File. Not. Found. Exception { some. Method("see previous slide"); } » some. Method may throw FNFExn (it says so) » another. Method won’t catch it (so it needs to say)

Javadoc @throws Tag § Add @throws tag to javadoc comment says that this method

Javadoc @throws Tag § Add @throws tag to javadoc comment says that this method throws an exception says what kind(s) of exception it throws says why it might be thrown /** *… * @throws File. Not. Found. Exception if user fails to provide a suitable * input file name within MAX_TRIES attempts. */

Example (Part 1) import java. util. Scanner; import java. io. File. Not. Found. Exception;

Example (Part 1) import java. util. Scanner; import java. io. File. Not. Found. Exception; /** * @throws File. Not. Found. Exception if 3 Nums. txt can't be opened */ public class Read 3 Numbers. From. File { public static void main(String[] args) throws File. Not. Found. Exception { int n 1, n 2, n 3; Scanner fin = new Scanner(new File("3 Nums. txt")); Continued next slide…

Example (Part 2) n 1 = fin. next. Int(); n 2 = fin. next.

Example (Part 2) n 1 = fin. next. Int(); n 2 = fin. next. Int(); n 3 = fin. next. Int(); fin. close(); System. out. println("The numbers in the file are: " + n 1 + ", " + n 2 + ", and " + n 3); } } no fin. next. Line(). Why not? » don’t expect file creator to press the enter key!

Names of Objects § Name of the file itself: 3 Nums. txt the file

Names of Objects § Name of the file itself: 3 Nums. txt the file has the numbers in it § Name of the Scanner: fin the Scanner is “attached” to the file » gets input from the file instead of from the user § Don’t get them confused: int n 1 = 3 Nums. txt. next. Int(); errors: illegal name/unknown name

Problem § We open the file for output § We print the sum to

Problem § We open the file for output § We print the sum to the file but when we look at the file, it’s empty! § Why? Buffering! takes a long time to find where to put the output, but the saving itself is (relatively) fast Print. Writer saves up output until it finds the place it needs to be saved to… … but if the program ends before it saves….

Output Files Start Empty § Output files get created if they didn’t already exist

Output Files Start Empty § Output files get created if they didn’t already exist § If an output file did already exist, its contents get erased once you open it (don’t need to print to it) § If you want to add to the old file Print. Writer fout = new Print. Writer( new File. Output. Stream(file. Name, true));

The File Class § Why do we write “new File(…)”? it’s not always a

The File Class § Why do we write “new File(…)”? it’s not always a new file, after all! § Creating a File object a program object to represent the file (remember, the Scanner/Print. Writer is for communicating with the file) actually just holds the name of the file, but… …it knows it’s supposed to be the name of a file

Yet Another Variable § You can create a variable for the File the. File

Yet Another Variable § You can create a variable for the File the. File = new File(file. Name); § You can ask the File object about the file does this file exist? can we read from it? can we write to it? is it a folder/directory? and more the. File. exists() the. File. can. Read() the. File. can. Write() the. File. is. Directory() these methods may throw Security. Exceptions, but they don’t need to be checked (they are Run. Time Exceptions)

Example: Listing all Files § Method to list all files in a given directory

Example: Listing all Files § Method to list all files in a given directory private static void list. Files. From(File dir) { if (dir. is. Directory()) { for (File file : dir. list. Files()) { System. out. println(file. get. Name()); } } else { System. out. println(dir. get. Name() + " is not a folder"); } }

Try with Resources § Better way to open/close files try (Scanner fin = new

Try with Resources § Better way to open/close files try (Scanner fin = new Scanner(chosen. File)) { … } catch (File. Not. Found. Exception fnf) { … } fin automatically closed when try block ends ditto if try block throws a different exception » which was a hidden bug in our earlier code!

Try with Multiple Resources § Separate resources with semi-colons: try (Scanner fin = new

Try with Multiple Resources § Separate resources with semi-colons: try (Scanner fin = new Scanner(in. File); Print. Writer fout = new Print. Writer(out. File)) { int sum = 0; while (fin. has. Next. Int()) { sum += fin. next. Int(); } fout. println("Sum was " + sum); } catch (File. Not. Found. Exception fnf) { System. err. println("File open error!"); }

Exercise § Revise this code to return Earth (code = 0 and distance =

Exercise § Revise this code to return Earth (code = 0 and distance = 149. 6) if file not found » don’t exit the program! public static Planet read. Planet. From. File(String file. Name) { try (Scanner fin = new Scanner(new File(file. Name))) { String a. Name = fin. next. Line(); int a. Code = fin. next. Int(); double a. Dist = fin. next. Double(); return new Planet(a. Name, a. Dist, a. Code); } catch (File. Not. Found. Exception fnf) { System. exit(1); } }

Questions? § Next week… review of course material on Tuesday » BRING QUESTIONS! second

Questions? § Next week… review of course material on Tuesday » BRING QUESTIONS! second midterm test on Thursday » during lecture hours » on Bright. Space » same rules as for test #1