40 likes | 150 Views
Arrays (Part FOUR). Working with Arrays And Files. File Processing Review. Writing Files FileWriter – Opens a file for writing PrintWriter – Allows programmer to use print and println Reading Files FileReader – Open an existing file for reading
E N D
Arrays (Part FOUR) Working with Arrays And Files
File Processing Review • Writing Files • FileWriter – Opens a file for writing • PrintWriter – Allows programmer to use print and println • Reading Files • FileReader – Open an existing file for reading • BufferedReader – Use a buffer to read full lines of text instead of one byte at a time. • Import classes from Java API import java.io.*; • Include throws IOException in method’s header publicstaticvoidmain(String[] args) throws IOException
Saving Contents of Array in a File • Create a FileWriter object and pass filename to the constructor FileWriter fwriter = newFileWriter(“C:\\values.txt”); • Create a PrintWriter object and pass a Filewriter reference to the constructor PrintWriter output = new PrintWriter (fwriter); • Use the PrintWriter object’s print and println methods in a loop to process the array for (int item: array) output.print(item); • Close the file • output.close();
Reading Contents Into an Array • Create a FileReader object and pass filename FileReader freader = newFileReader(“C:\\values.txt”); • Create a BufferedReader object and pass a FileReader reference to the constructor BufferedReader input = new BufferedReader (freader); • Use the readLine method, parse string and store in array str = input.readLine(); i =0; while (str != null) { array[i] = Integer.parseInt(str); i++; str = input.readLine(); } • Close the file • input.close();