1 / 4

Arrays (Part FOUR)

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

fagan
Télécharger la présentation

Arrays (Part FOUR)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays (Part FOUR) Working with Arrays And Files

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

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

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

More Related