Download presentation
Presentation is loading. Please wait.
1
Reading from a file and Writing to a file
Text I/O Reading from a file and Writing to a file
2
Add throws IOException to the main header
Things can happen while performing I/O, to handle this, Java needs the keywords throws IOException in the main method header public static void main (String[] args) throws IOException
3
Declaring Files The File class is on pages 329-331
It is best to use relative file paths (meaning: keep the file reading from & the program using it in the same folder) Declaring & assigning follows the reference data type’s standard dataType identifier = new dataType(); File inFile = new File(“filename.txt”);
4
Declaring Scanner to read from a File
The Scanner class is on pages Declaring & assigning follows the reference data type’s standard dataType identifier = new dataType(); Scanner input = new Scanner(fileNameIdentifier); Scanner input = new Scanner(new File(“filename.txt”)); Must close the Scanner to free the resource indentifier.close(); input.close();
5
Declaring a PrintWriter to Write to a File
The PrintWriter class is on pages Declaring & assigning follows the reference data type’s standard dataType identifier = new dataType(); PrintWriter out = new PrintWriter(fileNameIdentifier); PrintWriter out = new PrintWriter(new File(“filename.txt”)); Must close the PrintWriter to finish writing to the file indentifier.close(); out.close();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.