1 / 23

Using Data Files and Streams

Using Data Files and Streams. What is a data file? page 2 Data files and streams page 3 Example: Writing and reading a file page 4-7 Sequential data files – summary page 8-9 In-/out-classes in Java page 10-11 Reading numbers from a file page 12

stacyt
Download Presentation

Using Data Files and Streams

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. Using Data Files and Streams What is a data file? page 2 Data files and streams page 3 Example: Writing and reading a file page 4-7 Sequential data files – summary page 8-9 In-/out-classes in Java page 10-11 Reading numbers from a file page 12 Communication with the console page 13 The process of writing to / reading from a file page 14-15 Random access to the contents of a file page 16-17 Saving objects to a file / serialization page 18-21 The instanceof operator page 22 Summary – data files page 23 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  2. What is a Data File? • Up to now our programs have communicated with the world through the keyboard and the screen. • Programs can also communicate with data files. • All the files you work with in word processors, spreadsheet programs, and editors are data files. • Data files make it possible for the program to remember data from run to run. This is practical for us as users—we don't need to reenter data if we run a program several times with only minor changes in the input data. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  3. Data Files and Streams • We can think of the data that is sent between a program and a file as a stream. The data streams from a source to a destination. • We start by opening the stream. • We fill it up with data (“write” to the stream) if the stream is running from the program to the file. • If the stream is running in the opposite direction, the program empties the stream of data as the data is “read.” • Finally, we close the stream. • In the program, we start by attaching a stream object to the file we want to read from or write to. We say that we are opening the file. • This stream is the object we are working with in the program. We send read and write messages to the stream object. • When we finally close the stream object, this leads to the termination of the connection to the physical data file. We say that we are closing the file. • There are many classes that make stream objects. We make the stream objects in a somewhat special way: • an instance of one stream class will preferably become an argument for the constructor for another stream class. We can continue with this in several steps before we get a stream we are satisfied with. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  4. A Program Communicates with a Data File Tony Kingsley Ken Brown Margaret Gibson Matthew Johnson Peter Adams Tony Kingsley Ken Brown Margaret Gibson the program runs the program reads data from the data file the programwrites data to the data file nameFile.txt before the program runs nameFile.txt after the program has run the program reads data from the keyboard the user enters data Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  5. Reading All the Names from the File String filename = "nameFile.txt"; FileReader readConnToFile = new FileReader(filename); BufferedReader reader = new BufferedReader(readConnToFile); String result = "The register:\n"; String oneName = reader.readLine(); while(oneName != null) { // null means end-of-file result += oneName + "\n"; oneName = reader.readLine(); } JOptionPane.showMessageDialog(null, result); reader.close(); opens the file data should be buffered reads one line at a time, prints it to the screen closes the stream, and with that the file Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  6. Reading from File via Streams Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  7. Writing to a File FileWriter writeConnToFile = new FileWriter(filename, true); PrintWriter printer = new PrintWriter(new BufferedWriter(writeConnToFile)); String newName = ”Peter Hill”; printer.println(newName ); printer.close(); opens the file data should be buffered, and we want to use the well known println() method writes one line to the stream closes the stream, and the file with that Show program listing 11.1 pp. 310-311. Solve the problems, pp. 314 and 315 (top and bottom). Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  8. Sequential Data Files - Summary • Sequential data files are opened for reading or writing. • Reading always starts at the beginning of the file. • Writing can happen at the beginning of the file or after what is already there from before. • For a file to be read, it has to exist in advance. • If a file to be written to does not already exist, it will be created automatically. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  9. Reading and Writing to a File Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  10. A Small Selection of the Input and Output Classes in JDK 1.0 Object Object OutputStream InputStream FileInputStream FileOutputStream FilterOutputStream PrintStream Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  11. A Small Selection of the Input and Output Classes in JDK 1.1 and Newer Versions of Java Object Object Writer Reader InputStreamReader BufferedReader FileReader PrintWriter BufferedWriter OutputStreamWriter FileWriter Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  12. Reading Numbers from a Data File • Input one line of numbers at a time, use the readLine() method. • To find the spaces in the string, use the java.util. StringTokenizer class. • A string is converted into a number using the familiar methods parseInt() and parseDouble(). Show program listing 11.2 page 321. Solve the problem, pp. 322-323. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  13. Communication with the Console • Printout is familiar: System.out.println() • Input from the console is about the same as input from a file: InputStreamReader readConnConsole = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(readConnConsole); System.out.print("Your first name: "); System.out.flush(); // flushes the buffer after print() is used String firstName = reader.readLine(); • In the console window: >java …the name of the class… Your first name: Ann Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  14. The Process of Writing to / Reading from a File Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  15. Data (Numbers) Transferred as Text versus Binary Data Transfer • Numbers are stored in the computer memory in binary representation. • At a data file, they may be saved as text, or they may keep their binary representation. • Numbers transferred as text • The data file may be read by humans using an editor. • The conversion ("formatting") to / from binary representation takes time. • If decimal numerals should keep their accuracy, a double should be written with 15 digits. • Numbers transferred binary • The data file is not readable by humans. • The bytes are transferred directly without conversion. • No time is used for conversion. • The space required is the same at the data file as in the memory. • Interfaces in the Java API usable for binary transfer • DataInput • DataOutput Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  16. Random Access to the Contents of a File • An instance of the class RandomAccessFile is linked to a file that can be opened for both reading and writing. • We can move the file pointer to any position whatsoever in this file. • The RandomAccessFile class implements the interfaces for binary data transfer. • Constructor: • RandomAccessFile(String fileName, String mode) • mode = ”r” or ”rw” • Methods, all may throw IOException: • long getFilePointer(), void seek(long pos), long length() • void close() • char readChar(), int readInt(), double readDouble() • void writeChar(int character), void writeInt(int number), void writeDouble(double decimalNumeral) Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  17. An Example /* reads the whole file */ file.seek(0); // moves to the beginning of the file try { while (true) { // stops when EOFException is thrown int t = file.readInt(); System.out.println(t); } } catch (EOFException e) { } file.close(); } catch (Exception e) { System.out.println("Error: " + e); } } } import java.io.*; class DirectAccessFile { public static void main(String[] args) { try { RandomAccessFile file = new RandomAccessFile("DirectFile.dat", "rw"); /* writes 10 integers to the file */ for (int i = 0; i < 10; i++) file.writeInt(i); long fileLength = file.length(); System.out.println( "The file is " + fileLength + " bytes long."); /* * moves the file pointer to integer no. 7, reads i, * multiplies it by 10, and rewrites it to the file. */ file.seek(6 * 4); // moves past 6 integers, each 4 bytes int number = file.readInt(); number *= 10; file.seek(6 * 4); // moves the filepointer "back" file.writeInt(number); /* Printout:: The file is 40 bytes long. 0 1 2 3 4 5 60 7 8 9 */ Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  18. How Saving a Large Object at a File? • We want to save an instance of the RenovationProject (chap. 10) at file: class RenovationProject { private String name; private ArrayList allSurfaces = new ArrayList(); private ArrayList allPaints = new ArrayList(); • We have to split the object into smaller parts, and then save each value, for example in this way: write the number of surfaces to the file for (int i = 0; i < project. getNoOfSurfaces(); i++) { Surface theSurface = project.getSurface(i); write theSurface's name, length and width, and the name of the paint type, to the file } do the same for all paints • By reading we have to do the reverse process. • Or is there another way - ? Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  19. Serialization • Objects may be serialized. • The whole object is saved in one single statemment. • The file is not readable by humans in an editor. • The file is sequential and is open for reading or writing. • Writing the myApartment object to file: FileOutputStream outstream = new FileOutputStream("apartment1.ser"); ObjectOutputStream out = new ObjectOutputStream(outstream); out.writeObject(myApartment); // (class constants and class variables are not stored) out.close(); • Reading the object: FileInputStream instream = new FileInputStream("apartment1.ser"); ObjectInputStream in = new ObjectInputStream(instream); RenovationProject myApartment = (RenovationProject) in.readObject(); in.close(); Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  20. What Is Required for an Object to be Serialized? • Classes describing these objects have to implement the java.io.Serializable interface • Very easy! The interface doesn't contain any methods at all. • In our case: • class Surface implements java.io.Serializable { • class Paint implements java.io.Serializable { • class RenovationProject implements java.io.Serializable { • Almost every class in the Java API implements Serializable • What happens in the serialization process? • Instance variables are saved, class variables are not saved. • Information about every single class, included version no., is saved. • A reference to an object implies that the object is saved the first time this reference is found. The object then gets a serial number (from this is the name of the process; serialization). The next time the same reference is found, this serial number is used. • If the version of the class is not the same when the data are read as it was when they were written, an InvalidClassException is thrown. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  21. Show Program Listing 11.4 pp. 330-331 Solve the problems, pp. 334-335. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  22. The instanceof operator • A binary operator. • The value of the expression is true if the object is an instance of the class, or of a subclass of the class. • If the second operand is an interface, the object has to be an instance of a class (or of a subclass of a class) that implements this interface. • The operator has the same priority as the other comparison operators. • Examples (the classes implements Serializable): • Paint m1 = new Paint("Heimdal Extra", 3, 10, 100); • m1 instanceof Paint true • m1 instanceof Surface false • m1 instanceof Serializable true • m1 instanceof Object true operand1 instanceof operand2 reference class or interface Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  23. Sequential data files with data transferred as text (section 11.1-11.7) The file is opened for reading or writing. A program reads one line at a time by using readLine(). A program writes by using print() and println(). Numerical data are converted to/from text. The console is a special case of this type of file. May create a file of this type with an editor. Binary data transfer (section 11.8) Data, both text and numbers, are transferred without conversion. A file of this type has to be created by a Java-program made for this purpose. Files with random access(section 11.9) The file may at the same time be opened for reading and writing. The file is not sequential: The file pointer may be moved forwards and backwards. Data are transferred binary. In an editor a human being will only be able to read data of char type. Serialization (section 11.10) This process reads or writes whole objects. The file is handled in a sequential way. The data are not readable in an editor (except for texts which could be recognized among very much other things). Summary - Data Files Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

More Related