1 / 63

Files and Streams

Files and Streams. OBJECTIVES. In this chapter you will learn: Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream. Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream.

sylvie
Download Presentation

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. Files and Streams

  2. OBJECTIVES In this chapter you will learn: • Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream. • Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream. • Write text data to a file and read them back from the file, using PrintWriterand BufferedReader. • Read a text file using Scanner • Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream

  3. Introduction • Storage of data in variables and arrays is temporary • Files used for long-term retention of large amounts of data, even after the programs that created the data terminate • Persistent data – exists beyond the duration of program execution • Files stored on secondary storage devices • Stream – ordered data that is read from or written to a file

  4. Data Hierarchy • Computers process all data items as combinations of zeros and ones • Bit – smallest data item on a computer, can have values 0 or 1 • Byte – 8 bits • Characters – larger data item • Consists of decimal digits, letters and special symbols • Character set – set of all characters used to write programs and represent data items • Unicode – characters composed of two bytes

  5. Data Hierarchy • Fields – a group of characters or bytes that conveys meaning • Record – a group of related fields • File – a group of related records

  6. Fig. 14.1 | Data hierarchy.

  7. There are two general types of files you need to learn about: textfiles and binaryfiles… •A text, or character-based, file stores information using unicode character representations. Text files can be viewed with a standard editor or word processing program but cannot be manipulated arithmetically without requiring special conversion routines. •A binary file stores numerical values using the internal numeric binary format specified by java. A Java program can read a binary file to get numeric data, manipulate the data arithmetically, and write the data to a binary file without any intermediate conversions.

  8. FileOperations There are three basic operations that you will need to perform when working with disk files: •Open the file for input or output. •Process the file, by reading from or writing to the file. •Close the file.

  9. Files and Streams • Java views each file as a sequential stream of bytes • Operating system provides mechanism to determine end of file • End-of-file marker • Count of total bytes in file • Java program processing a stream of bytes receives an indication from the operating system when program reaches end of stream Fig. 14.2 | Java’s view of a file of n bytes.

  10. Files and Streams • File streams • Byte-based streams – stores data in binary format • Binary files – created from byte-based streams, read by a program that converts data to human-readable format. 5 is (101) • Character-based streams – stores data as a sequence of characters • Text files – created from character-based streams, can be read by text editors. 5 is (00000000 00110101) – unicode representation • Java opens file by creating an object and associating a stream with it

  11. Class File • Class File useful for retrieving information about files and directories from disk • Objects of class File do not open files or provide any file-processing capabilities

  12. Creating File Objects • Class File provides four constructors: • Takes String specifying name and path (location of file on disk) • Takes two Strings, first specifying path and second specifying name of file • Takes File object specifying path and String specifying name of file • Takes URI object specifying name and location of file • Different kinds of paths • Absolute path – contains all directories, starting with the root directory, that lead to a specific file or directory • Relative path – normally starts from the directory in which the application began executing

  13. File methods.(Part 1 of 2)

  14. | File methods.(Part 2 of 2)

  15. Use File method isFile to determine whether a File object represents a file (not a directory) before attempting to open the file. Error-Prevention Tip

  16. Demonstrating Class File • Common File methods • exists – return true if file exists where it is specified • isFile – returns true if File is a file, not a directory • isDirectory – returns true if File is a directory • getPath – return file path as a string • list – retrieve contents of a directory • Separator character – used to separate directories and files in a path • Windows uses \ • UNIX uses / • Java process both characters, File.pathSeparator can be used to obtain the local computer’s proper separator character

  17. Create new File object; user specifies file name and path Returns true if file or directory specified exists Retrieve name of file or directory Retrieve path entered as a string Returns true if name is a file, not a directory Returns true if name is a directory, not a file Returns true if path was an absolute path Retrieve time file or directory was last modified (system-dependent value) Retrieve length of file in bytes Retrieve parent directory (path where File object’s file or directory can be found) Retrieve absolute path of file or directory Outline FileDemonstration .java (1 of 2)

  18. Returns true if File is a directory, not a file Retrieve and display contents of directory Outline FileDemonstration .java (2 of 2)

  19. Outline FileDemonstration Test.java (1 of 3)

  20. Outline FileDemonstration Test.java (2 of 3)

  21. Outline FileDemonstration Test.java (3 of 3)

  22. Using \ as a directory separator rather than \\ in a string literal is a logic error. A single \ indicates that the \ followed by the next character represents an escape sequence. Use \\ to insert a \ in a string literal. Common Programming Error

  23. Low-Level File I/O• • To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. • A stream is a sequence of data items (sequence of characters or bytes) used for program input or output. Java provides many different input and output stream classes in the java.io API. • A file stream is an object that enables the flow of data between a program and some I/O device or file

  24. Low-Level File I/O –Java has two types of streams: an input stream and an output stream. –If the data flows into a program, then the stream is called an input stream –If the data flows out of a program, then the stream is called an output stream

  25. Opening a File • A file stream provides a connection between your program and the outside world. Opening a file makes the connection between a logical program object and a physical file via the file stream. FileOutputStream data Logical File Object Physical Disk File FileInputStream data

  26. Streams for Low-Level File I/OBinary File Stream Classes (Byte I/O) • FileInputStreamTo open a binary input stream and connect it to a physical disk file: • Constructor takes a String or File object. • Method to read: int read() OR void read(byte[]) • FileOutputStreamTo open a binary output stream and connect it to a physical disk file: • Constructor takes a String or File object. • Method to write: void write( int ) OR void write( byte[] ) • BOTH CLASSES READ/WRITE ONE BYTE AT A TIME

  27. Streams for Low-Level File I/OBinary File Stream Classes (Byte I/O) DataInputStreamTo read binary data from a stream DataOutputStreamTo write binary data to a stream

  28. A File Has Two Names •Every input file and every output file used by a program has two names: 1.The real file name used by the operating system 2.The name of the stream that is connected to the file •The actual file name is used to connect to the stream •The stream name serves as a temporary name for the file, and is the name that is primarily used within the program

  29. Opening a File A file stream provides a connection between your program and the outside world. Opening a file makes the connection between a logical program object and a physical file via the file stream.

  30. Opening a Binary File for Output Using the FileOutputStream class, create a file stream and connect it to a physical disk file to open the file. We can output only a sequence of bytes.

  31. Opening a Binary File for Output Import java.io.*; public class TestFileOuputStream{ public static void main (String [] args) throws IOException{ //set up file and stream File F = new File("sample1.data"); File OutputStream OutF = new FileOutputStream(F ); //data to save byte[] A = {10, 20, 30, 40,50, 60, 70, 80}; //write the whole byte array at once to the stream OutF.write(A ); //output done, so close the stream OutF.close();}}

  32. Opening a Binary File for Input Using the FileInputStream class, create a file stream and connect it to a physical disk file to open the file.

  33. Opening a Binary File for Input Import java.io.*; public class TestFileInputStream{ public static void main (String [] args) throws IOException { //set up file and stream File G = new File("sample1.data"); FileInputStream InG = new FileInputStream(G); / /set up an array to read data in Int fileSize= (int) G.length(); byte[] B = newbyte[fileSize]; //read data in and display them InG.read(B); for(int i = 0; i < fileSize; i++) { System.out.println(B[i]); } //input done, so close the stream InG.close() ; } }

  34. import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }

  35. Streams for High-Level File I/O • •FileOutputStream and DataOutputStream are used to output primitive data values • •FileInputStream and DataInputStream are used to input primitive data values • •To read the data back correctly, we must know the order of the data stored and their data types

  36. Setting up DataOutputStreamA standard sequence to set up a DataOutputStreamobject: • Create a File object • Create a FileOutputStream object wrapped around the File object • Create a DataOutputStream object wrapped around the FileOutputStream object. • DataOutputSStream out = new DataOutputStream( new FileOutputStream( new File(“sample.dat”)));

  37. Import java.io.*; public class TestDataOutputStream{ public static void main (String[] args) throws IOException { //set up file and stream File F = newFile("sample3.data"); FileOutputStreamOutF= newFileOutputStream(F ); DataOutputStreamDF = newDataOutputStream(OutF); //write values of primitive data types to the stream DF. DF.writeByte(12); DF.writeInt(1234); DF.writeLong(9876543); DF.writeFloat(1234F); DF.writeDouble(1234.4565345); DF.writeChar('A'); DF.writeBoolean(false); //output done, so close the stream DF.close(); } }

  38. Setting up DataInputStreamA standard sequence to set up a DataInputStreamobject: • Create a File object • Create a FileInputStream object wrapped around the File object • Create a DataInputStream object wrapped around the FileInputStream object. • DataInputStream in = new DataInputStream( new FileInputStream( new File(“sample.dat”)));

  39. Import java.io.*; public class TestDataInputStream { public static void main (String[] args) throws IOException{ //set up in DataStream File G = new File("sample3.data"); FileInputStream InF = new FileInputStream(G ); DataInputStream DF = new DataInputStream(InF); //read values back from the stream and display them System.out.println(DF.readByte()); System.out.println(DF.readInt()); System.out.println(DF.readLong()); System.out.println(DF.readFloat()); System.out.println(DF.readDouble()); System.out.println(DF.readChar()); System.out.println(DF.readBoolean()); //input done, so close the stream DF.close(); } }

  40. /*output after reading file sample3.dtat“ 12 1234 9876543 1234.0 1234.4565345 A true ************************

  41. Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly

  42. Text file Input and Output • Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor • To output data as a string to file, we use a FileWriter object. • To input data from a textfile, we use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting text files

  43. Text file Input and Output The following classes will be covered for textfile I/O: • FileReader • FileWriter • Scanner • Formatter

  44. Text File Stream Classes • FileReader - To open a character input stream and connect it to a physical disk file • Constructor param : File object OR String • Method to read : int read() • FileWriter - To open a character output stream and connect it to a physical disk file • Constructor param : String • Method to write: void write( int)

  45. Text File Stream Classes import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;  public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null;  try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt");  int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }}

  46. Character Streams that Use Byte Streams Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

  47. Text File Stream Classes • Scanner – to read text files, the constructor expects a file object. • Formatter – to write text files, the constructor expects a String object.

  48. Java imposes no structure on a file, records do not exist as part of the Java language Programmer must structure files Formatter class can be used to open a text file for writing Pass name of file to constructor If file does not exist, will be created If file already exists, contents are truncated (discarded) Use method format to write formatted text to file Use method close to close the Formatter object (if method not called, OS normally closes file when program exits) Text File Stream Classes

  49. Possible exceptions SecurityException – occurs when opening file using Formatter object, if user does not have permission to write data to file FileNotFoundException – occurs when opening file using Formatter object, if file cannot be found and new file cannot be created NoSuchElementException – occurs when invalid input is read in by a Scanner object FormatterClosedException – occurs when an attempt is made to write to a file using an already closed Formatter object

More Related