Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " 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."— Presentation transcript:

1

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

3  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 3

4  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 4

5  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 5

6  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 6

7  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 7

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

9 Java Programming File I/O9 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. P rogram uses an input stream to read data from a source, one item at a time: Reading information into a program

10 Java Programming File I/O10 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.

11 Java Programming File I/O 11 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(); }

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

13 Java Programming File I/O13 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.Buffered ReaderPrint Writer 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(); }

14 Java Programming File I/O14 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(); // … }

15 Java Programming File I/O15 // 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 A ccount(name, id, balance); }

16 Java Programming File I/O16 The Scanner classThe 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.

17 Java Programming File I/O17 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(); }

18 Java Programming File I/O 18

19 Java Programming File I/O 19

20 Java Programming File I/O 20

21 Java Programming File I/O 21

22 Java Programming File I/O 22

23  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 23

24 Java Programming File I/O 24

25  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 25

26 Java Programming File I/O 26

27 Java Programming File I/O 27

28 Java Programming File I/O 28

29 Java Programming File I/O 29

30  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 30

31  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 31

32 Java Programming File I/O 32

33 Java Programming File I/O 33

34  Process random access file  Sequentially  Randomly Java Programming File I/O 34

35  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 35

36  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 36

37 Java Programming File I/O 37

38  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 38


Download ppt " 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."

Similar presentations


Ads by Google