1 / 38

Java Programming File Input and Output

Java Programming File Input and Output. Objectives. Learn about computer files Use the Path class Learn about Streams Buffers file organization Use Java’s IO classes to write to and read from a file Create and use sequential data files Learn about random access files

saddison
Télécharger la présentation

Java Programming File Input and Output

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. Java Programming File Input and Output

  2. Objectives • Learn about computer files • Use the Path class • Learn about • Streams • Buffers • file organization • Use Java’s IO classes to write to and read from a file • Create and use sequential data files • Learn about random access files • Write records to a random access data file • Read records from a random access data file Java Programming File I/O

  3. Objectives (cont'd.) • We have seen how objects communicate with each other. Program often need to communicate with the outside world. The means of communication are input (such as a keyboard) and output (such as the computer screen). Programs can also communicate through stored data, such as files. Java Programming File I/O

  4. Understanding Computer Files • Volatile (Unstable) storage • Computer memory or random access memory (RAM) • Temporary • Nonvolatile storage (having the property of retaining data when electrical power fails or is turned off. • Not lost when computer loses power • Permanent • Computer file • Collection of information stored on nonvolatile device in computer system Java Programming File I/O

  5. Understanding Computer Files (cont'd.) • Permanent storage devices • Hard disks • Zip disks • USB drives • Reels or cassettes of magnetic tape • Compact discs • Categories of files by the way they store data • Text files • Binary files Java Programming File I/O

  6. Understanding Computer Files (cont'd.) • Data files • Contain facts and figures • Program files or application files • Store software instructions • Root directory • Folders or directories • Path • Complete list of disk drive plus hierarchy of directories in which file resides Java Programming File I/O

  7. Understanding Computer Files (cont'd.) • Work with stored files in application • Determine whether and where file exists • Open file • Write information to file • Read data from file • Close file • Delete file Java Programming File I/O

  8. I/O Streams A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Java Programming File I/O

  9. Reading information into a program Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. Program uses an input stream to read data from a source, one item at a time: Java Programming File I/O

  10. Writing information from a program. A program uses an output stream to write data to a destination, one item at time: The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also another program, a peripheral device, a network socket, or an array. Java Programming File I/O

  11. Example: Reading & Writing One Character at a time Notice that there is a block of code preceded by the keyword try and another block of code preceded by the keyword finally. This is to ensure that the code in the finally block gets executed, even if the code within the try block causes an exception to be thrown. import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;   public class IOTest { public static void copyCharacters() throws IOException { FileReader inputStream = null; FileWriter outputStream = null;   try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("xanadu_output.txt");   int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } Java Programming File I/O

  12. Reading in Lines of Characters Scanner inFile = new Scanner(new File(“in.txt")); String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); // … } Java Programming File I/O

  13. Reading and Writing one line a time import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException;   public static void copyLines() throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null;   try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));   String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } Copy Characters example to use line-oriented I/O. To do this, we have to use two classes we haven't seen before, Buffered Reader and Print Writer. Java Programming File I/O

  14. File I/O • Use Scanner with File: • Scanner inFile = new Scanner(new File(“in.txt”)); • Similar to Scanner with System.in: • Scanner keyboard = new Scanner(System.in); • Reading in • Scanner inFile = new Scanner(new File(“in.txt")); • int number; • while (inFile.hasInt()) • { • number = inFile.nextInt(); • // … • } Java Programming File I/O

  15. Multiple Types on One Line // Name, id, balance Scanner inFile = new Scanner(new File(“in.txt")); while (inFile.hasNext()) { name = inFile.next(); id = inFile.nextInt(); balance = inFile.nextFloat(); // … new Account(name, id, balance); } -------------------- String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); Scanner parseLine = new Scanner(line) // Scanner again! name = parseLine.next(); id = parseLine.nextInt(); balance = parseLine.nextFloat(); // … new Account(name, id, balance); } Java Programming File I/O

  16. Scanning The Scanner class is available in Java 5 (JDK 1.5). It provides methods to convert text into appropriate Java types (integer, float, etc). A scanner splits text into a succession of tokens (text representations of data values) according to specific rules. For example, in the String object "ab*cd 12.34 253", "ab*cd" is a String token, "12.34" is a double token and "253" is an integer token. Java Programming File I/O

  17. Scanner Example 1 By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators. The program that reads the individual words in xanadu.txt and prints them out, one per line. import java.io.*; import java.util.Scanner;   public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));   while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } Java Programming File I/O

  18. Retrieving Information about a Path Java Programming File I/O

  19. Retrieving Information about a Path (cont’d.) Java Programming File I/O

  20. Checking File Accessibility Java Programming File I/O

  21. Deleting a Path Java Programming File I/O

  22. Determining File Attributes Java Programming File I/O

  23. File Organization, Streams, and Buffers • Retain data for any significant amount of time • Save on permanent, secondary storage device • Businesses store data in hierarchy • Character • Field • Record • Files • Sequential access file • Each record stored in order based on value in some field Java Programming File I/O

  24. File Organization, Streams, and Buffers (cont'd.) Java Programming File I/O

  25. File Organization, Streams, and Buffers (cont'd.) • Open file • Create object • Associate stream of bytes with it • Close file • Make it no longer available to application • Should always close every file you open • Stream • Bytes flowing into program from input device • Bytes flow out of application to output device • Most streams flow in only one direction Java Programming File I/O

  26. File Organization, Streams, and Buffers (cont'd.) Java Programming File I/O

  27. Java Programming File I/O

  28. Writing to a File (cont’d.) Java Programming File I/O

  29. Java Programming File I/O

  30. Learning about RandomAccess Files • Sequential access files • Access records sequentially from beginning to end • Good for batch processing • Same tasks with many records one after the other • Inefficient for many applications • Realtime applications • Require immediate record access while client waits Java Programming File I/O

  31. Learning about RandomAccess Files (cont'd.) • Random access files • Records can be located in any order • Also called direct access or instant access files • File channel object • Avenue for reading and writing a file • You can search for a specific file location and operations can start at any specified position • ByteBuffer wrap() method • Encompasses an array of bytes into a ByteBuffer Java Programming File I/O

  32. Learning about RandomAccess Files (cont'd.) Java Programming File I/O

  33. Java Programming File I/O

  34. Reading Records froma Random Access File • Process random access file • Sequentially • Randomly Java Programming File I/O

  35. Accessing a Random Access File Sequentially • ReadEmployeesSequentially application • Reads through 1000-record RandomEmployees.txt file sequentially in a for loop (shaded) • When ID number value is 0 • No user-entered record stored at that point • Application does not bother to print it Java Programming File I/O

  36. Accessing a Random Access File Randomly • Display records in order based on key field • Do not need to create random access file • Wastes unneeded storage • Instead sort records • Benefit of using random access file • Retrieve specific record from file directly • Without reading through other records Java Programming File I/O

  37. Java Programming File I/O

  38. Summary • Files • Objects stored on nonvolatile, permanent storage • File class • Gather file information • Java views file as a series of bytes • Views stream as object through which input and output data flows • DataOutputStream class • Accomplish formatted output • Random access files Java Programming File I/O

More Related