Reading from a file and Writing to a file Text I/O Reading from a file and Writing to a file
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
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”);
Declaring Scanner to read from a File The Scanner class is on pages 334-337 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();
Declaring a PrintWriter to Write to a File The PrintWriter class is on pages 332-334 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();