Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reading from a file and Writing to a file

Similar presentations


Presentation on theme: "Reading from a file and Writing to a file"— Presentation transcript:

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();

6


Download ppt "Reading from a file and Writing to a file"

Similar presentations


Ads by Google