Text File Input & Output Methods

Text File Input & Output Methods
Slide Note
Embed
Share

In this educational content, learn about the fundamental concepts of file handling in Java programming. Explore the importance of understanding the distinction between files and streams, utilizing Scanners and PrintWriters, managing file streams effectively, and handling text files. Discover how to work with input and output streams, system streams, and file streams, as well as essential program variables and required types for file handling operations. Gain insights into the significance of utilizing files for data permanence, reusability, and accuracy. Enhance your knowledge of working with text files and leveraging their advantages in programming tasks.

  • File handling
  • Java programming
  • Text files
  • Input/output streams
  • Programming basics

Uploaded on Mar 21, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Text File Input & Output

  2. Outcomes Know the difference between files and streams Use a Scanner to read from a file add throws annotations to methods use the hasNext family of methods to read every element in a file Use a PrintWriter 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

  3. 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) System.out keyboard Program monitor

  4. File Streams Can get program to read from/write to files connect Scanner to a file instead of System.in use a PrintWriter instead of System.out carry information to/from files fin fout (Scanner) (PrintWriter) fileIn.txt myprog.exe fileOut.txt

  5. 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 PrintWriter for writing to file

  6. 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.PrintWriter; import java.io.FileNotFoundException; we ll need this last one, too

  7. 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 Twas brillig and the slithy toves 3Numbers.txt poem.txt

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

  9. 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 120 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

  10. 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.nextInt(); String word = KBD.next(); double x = KBD.nextDouble(); String line = KBD.nextLine();

  11. 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: Reverse600.java Can we make that easier? 677 924 528 738 755 411 414 147 739 167 myData.txt

  12. 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 String line = KBD.nextLine(); Scanner stringInput = new Scanner(line); from a file File theFile = new File("myData.txt"); Scanner fileInput = new Scanner(theFile); Remember to import java.io.File;

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

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

  15. The File Data Type Import from java.io import java.io.File; Represents a file on your computer constructor gives name of file File theFile = new File("myData.txt"); NOTE: myData.txt shouldalready exist it s a newobject representing the file but it might not it might actually represent a new file

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

  17. The Scanner Tell the Scanner to read from the file Scanner fileInput = new Scanner(theFile); Problem: FileNotFoundException must be declared or caught need a try-catch block for this exception checked exception NOT a RuntimeException

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

  19. Reading the File Name Can ask the user for the name of the file user gets to choose what file to use use a Scanner connected to System.in for input Scanner kbd = new Scanner(System.in); System.out.print("Enter file name: "); fileName = KBD.nextLine(); Scanner fileInput = getScannerFor(fileName); program ends if named file doesn t exist

  20. Requesting Alternatives Method requests file names until one works private static Scanner getScanner() { while (true) { System.out.print("Enter file name: "); try { return new Scanner(new File(KBD.nextLine())); } catch (FileNotFoundException fnf) { System.out.println("I can't find that file!"); } } }

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

  22. Reading File Contents Reverse600 program reads 600 numbers count control: for loop JavaAverage 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

  23. While The File Has Data Can ask any Scanner if next thing exists hasNext returns true if there is a next element while (fileInput.hasNext()) { } use next / nextInt / etc. to get that element could also use hasNextInt, hasNextDouble, hasNextInt = hasNext and next is an int hasNextDouble = hasNext and next is a double while (fileInput.hasNextInt()) { ++count; sum += fileInput.nextInt(); }

  24. Saving All The Data Don t read into an array there might be too much data! Read into a List List<Integer> values = new ArrayList<>(); while (fileInput.hasNextInt()) { values.add(fileInput.nextInt()); } can now process data using List operations

  25. 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 (fileInput.hasNextInt()) { values.add(fileInput.nextInt()); } fileInput.close();

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

  27. 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 120 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

  28. PrintWriter 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 PrintStream But PrintWriter is better and it has all the same print methods makes printing to a file easy for us fileOutput.print("This is file output: "); fileOutput.println(sum);

  29. Connecting to an Output File Same as for connecting a Scanner File theFile = new File(fileName); PrintWriter fileOutput = new PrintWriter(theFile); Same problem FileNotFoundException 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

  30. Get The Printer Method Separate from main program get a PrintWriter or die trying! private static PrintWriter getPrinterFor(String fileName) { try { return new PrintWriter(new File(fileName)); } catch (FileNotFoundException fnf) { System.err.println("Cannot open " + fileName); 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.

  31. Writing to the File Send reversed numbers to the file after reading all the numbers into a List PrintWriter fileOutput = getPrinterFor("reversed.txt"); for (int i = values.size() 1; i >= 0; --i) { fileOutput.println(values.get(i)); } fileOutput.close(); don t forget to close the connection forget some numbers may be missing! recall: output buffering

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

  33. 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 PrintWriter connects if you don t print anything, file still gets erased

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

  35. Looking for Files NetBeans looks in the project folder Week09 program looks in Week09 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: dataFolder/myData.txt The average of the 25 numbers you entered is 70.04

  36. Files & Folders Files exist inside folders src Lab03 myProg.java NetBeans Projects J: classes myProg.class Lab05 Lab05Data.txt J:\ NetBeans Projects\Lab03\src\myProg.java J:\ NetBeans Projects\Lab05\Lab05Data.txt

  37. Files & Folders If you just give the name of the file myData.txt NetBeans looks in the project folder not the src folder! Looks here not there src Lab03 But you can specify other folders absolute/relative paths

  38. File Paths Somewhat system dependent but can always use / to separate folder names remember to escape \ if inside quote marks Absolute path J:/NetBeans Projects/Lab05/Lab05Data.txt Relative path (from L03 folder) ../Lab05/Lab05Data.txt

  39. 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! Lab03 NetBeans Projects J: Put data files in project folder Use relative paths Project Folder .. ../..

  40. Exercise Given this directory structure, how would we refer to myProg.java from a program in Lab03? src Lab03 myProg.java NetBeans Projects J: classes myProg.class Lab05 Lab05Data.txt

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

  42. Not Catching the FNFException An error message when we try to open a file java.io.FileNotFoundException must be caught or declared to be thrown FNFExn is not a RuntimeException RuntimeExceptions are nicer don t need to say you re not catching them you need to catch the FNFException or sayyou re not going to catch it!

  43. Declaring an Exception Say you re not catching it public static void someMethod(String someParam) throws FileNotFoundException { NOTE where it is beforethe body s opening brace Note: throws instead of throw throw is a command tells computer to do something throws is a description says what this method sometimes does

  44. When to Use a throws Clause Use throws FileNotFoundException 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 anotherMethod() throws FileNotFoundException { someMethod("see previous slide"); } someMethod may throw FNFExn (it says so) anotherMethod won t catch it (so it needs to say)

  45. 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 FileNotFoundException if user fails to provide a suitable * input file name within MAX_TRIES attempts. */

  46. Example (Part 1) import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /** * @throws FileNotFoundException if 3Nums.txt can't be opened */ public class Read3NumbersFromFile { public static void main(String[] args) throws FileNotFoundException { int n1, n2, n3; Scanner fin = new Scanner(new File("3Nums.txt")); Continued next slide

  47. Example (Part 2) n1 = fin.nextInt(); n2 = fin.nextInt(); n3 = fin.nextInt(); fin.close(); System.out.println("The numbers in the file are: " + n1 + ", " + n2 + ", and " + n3); } } no fin.nextLine(). Why not? don t expect file creator to press the enter key!

  48. Names of Objects Name of the file itself: 3Nums.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 n1 = 3Nums.txt.nextInt(); errors: illegal name/unknown name

  49. 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 PrintWriter saves up output until it finds the place it needs to be saved to but if the program ends before it saves .

  50. 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 PrintWriter fout = new PrintWriter( new FileOutputStream(fileName, true));

More Related Content