Presentation is loading. Please wait.

Presentation is loading. Please wait.

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.

Similar presentations


Presentation on theme: "I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1."— Presentation transcript:

1 I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

2 In fact, aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real applications of Java are not text-based, console programs. they are graphically oriented applets that rely upon Javas Abstract Window Toolkit (AWT) for interaction with the user. Javas support for console I/O is limited and somewhat awkward to useeven in simple example programs. Text-based console I/O is just not very important to Java programming. 12 January 2014 Smitha N. Pai, CSE Dept. 2

3 Streams Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Same I/O classes and methods can be applied to any type of device.. 12 January 2014 Smitha N. Pai, CSE Dept. 3

4 Streams(contd.) Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Output stream may refer to the console, a disk file, or a network connection. Streams deal with input/output without having every part of your code understand the difference between a keyboard and a network. Java implements streams within class hierarchies defined in the java.io package. 12 January 2014 Smitha N. Pai, CSE Dept. 4

5 Byte Streams and Character Streams Java 2 defines two types of streams: byte and character. Byte streams provide means for handling input and output of bytes and are used for reading or writing binary data. Character streams handles input and output of characters. They use Unicode and, therefore, can be internationalized. Character streams are more efficient than byte streams. At the lowest level, all I/O is byte-oriented 12 January 2014 Smitha N. Pai, CSE Dept. 5

6 The Byte Stream Classes Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses, that handle the differences between various devices, such as disk files, network connections, and even memory buffers. to use the stream classes, you must import java.io. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), 12 January 2014 Smitha N. Pai, CSE Dept. 6

7 which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes. The Character Stream Classes Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer, which define several key methods that the other stream classes implement. 12 January 2014 Smitha N. Pai, CSE Dept. 7

8 These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. Two of the most important methods are read( ) and write( ),which read and write characters of data, respectively. These methods are overridden by derived stream classes First slide is Byte Stream classes Second slide is the character stream I/O classes 12 January 2014 Smitha N. Pai, CSE Dept. 8

9 12 January 2014 Smitha N. Pai, CSE Dept. 9

10 12 January 2014 Smitha N. Pai, CSE Dept. 10

11 The Predefined Streams java.lang package defines a class called System, which encapsulates several aspects of the run-time environment. Using some of its methods, you can do the settings of various properties associated with the system. System also contains three predefined stream variables, in, out, and err. These fields are declared as public and static within System. They can be used by any other part of the program and without reference to a specific System object. 12 January 2014 Smitha N. Pai, CSE Dept. 11

12 System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. These streams may be redirected to any compatible I/O device. System.in is an object of type InputStream System.out and System.err are objects of type PrintStream. These are byte streams, used to read and write characters from and to the console. 12 January 2014 Smitha N. Pai, CSE Dept. 12

13 Reading Console Input Console input is accomplished by reading from System.in. To obtain character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Constructor is shown here: BufferedReader(Reader inputReader) 12 January 2014 Smitha N. Pai, CSE Dept. 13

14 inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) 12 January 2014 Smitha N. Pai, CSE Dept. 14

15 System.in refers to an object of type InputStream, it can be used for inputStream. The following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Reading Characters To read a character from a BufferedReader, use read( ). int read( ) throws IOException 12 January 2014 Smitha N. Pai, CSE Dept. 15

16 It reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. It can throw an IOException. // Use a BufferedReader to read characters from the console. import java.io.*; class BRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 January 2014 Smitha N. Pai, CSE Dept. 16

17 System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Enter characters, 'q' to quit. 123abcq 1 2 3 a b c q System.in line buffered, by default. This means that no input is actually passed to the program until you press ENTER. 12 January 2014 Smitha N. Pai, CSE Dept. 17

18 Reading Strings To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here: String readLine( ) throws IOException It returns a String object. import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 January 2014 Smitha N. Pai, CSE Dept. 18

19 String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } import java.io.*; //A tiny Editor class TinyEdit { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 January 2014 Smitha N. Pai, CSE Dept. 19

20 String str[] = new String[100]; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.println("\nHere is your file:"); // display the lines for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); } }. 12 January 2014 Smitha N. Pai, CSE Dept. 20

21 Here is a sample run: Enter lines of text. Enter 'stop' to quit. This is line one. This is line two. Just create String objects. stop Here is your file: This is line one. This is line two. Just create String objects 12 January 2014 Smitha N. Pai, CSE Dept. 21

22 Writing Console Output PrintStream is an output stream derived from OutputStream, it implements the low-level method write( ). write( ) can be used to write to the console: void write(int byteval) This method writes to the stream the byte specified by byteval. byteval is declared as an integer, only the low- order eight bits are written. 12 January 2014 Smitha N. Pai, CSE Dept. 22

23 class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } Writes A to the console and adds a new line. 12 January 2014 Smitha N. Pai, CSE Dept. 23

24 File The File class does not operate on stream It deals directly with files and the file system. File class does not specify how information is retrieved from or stored in files; it describes the properties of a file itself. A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. 12 January 2014 Smitha N. Pai, CSE Dept. 24

25 A directory in Java is treated as a File with one additional propertya list of filenames that can be examined by the list( ) method. The following constructors can be used to create File objects: File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename) File(URI uriObj) Here, directoryPath is the path name of the file, filename is the name of the file, dirObj is a File object that specifies a directory, and uriObj is a URI object that describes a file. 12 January 2014 Smitha N. Pai, CSE Dept. 25

26 The following example creates three files: f1, f2, and f3. The first File object is constructed with a directory path as the only argument. The second includes two argumentsthe path and the filename. The third includes the file path assigned to f1 and a filename; f3 refers to the same file as f2. File f1 = new File("/"); File f2 = new File("/","autoexec.bat"); File f3 = new File(f1,"autoexec.bat"); import java.io.File; // Demonstrate File class FileDemo { static void p(String s) { System.out.println(s); } public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); p("File Name: " + f1.getName()); 12 January 2014 Smitha N. Pai, CSE Dept. 26

27 p("Path: " + f1.getPath()); p("Abs Path: " + f1.getAbsolutePath()); p("Parent: " + f1.getParent()); p(f1.exists() ? "exists" : "does not exist"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "is readable" : "is not readable"); p("is " + (f1.isDirectory() ? "" : "not" + " a directory")); p(f1.isFile() ? "is normal file" : "might be a named pipe"); p(f1.isAbsolute() ? "is absolute" : "is not absolute"); p("File last modified: " + f1.lastModified()); p("File size: " + f1.length() + " Bytes"); } 12 January 2014 Smitha N. Pai, CSE Dept. 27

28 File Name: COPYRIGHT Path: /java/COPYRIGHT Abs Path: /java/COPYRIGHT Parent: /java exists is writeable is readable is not a directory is normal file is absolute File last modified: 812465204000 File size: 695 Bytes 12 January 2014 Smitha N. Pai, CSE Dept. 28

29 isFile( ) returns false for some special files, such as device drivers and named pipes, so this method can be used to make sure the file will behave as a file. The isAbsolute( ) method returns true if the file has an absolute path and false if its path is relative. 12 January 2014 Smitha N. Pai, CSE Dept. 29

30 12 January 2014 Smitha N. Pai, CSE Dept. 30 Directories A directory is a File that contains a list of other files and directories. The isDirectory( ) method will return true when you create a File object and its directory. list( ) is called on the object to extract the list of other files and directories present inside.

31 Two forms are: String[ ] list( ) String[ ] list(FilenameFilter FFObj) The list of files is returned in an array of String objects. // Using directories. import java.io.File; class DirList { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println("Directory of " + dirname); 12 January 2014 Smitha N. Pai, CSE Dept. 31

32 String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + "/" + s[i]); if (f.isDirectory()) { System.out.println(s[i] + " is a directory"); } else { System.out.println(s[i] + " is a file"); } } } else { System.out.println(dirname + " is not a directory"); } 12 January 2014 Smitha N. Pai, CSE Dept. 32

33 Here is sample output from the program. Directory of /java bin is a directory lib is a directory demo is a directory COPYRIGHT is a file README is a file index.html is a file include is a directory src.zip is a file hotjava is a directory src is a directory 12 January 2014 Smitha N. Pai, CSE Dept. 33

34 Using FilenameFilter The list( ) method includes only those files that match a certain filename pattern, or filter. String[ ] list(FilenameFilter FFObj) FFObj is an object of a class that implements the FilenameFilter interface. FilenameFilter defines only a single method, accept( ), which is called once for each file in a list. boolean accept(File directory, String filename) 12 January 2014 Smitha N. Pai, CSE Dept. 34

35 The accept( ) method returns true for files in the directory specified by directory that should be included in the list (that is, those that match the filename argument), and returns false for those files that should be excluded. import java.io.*; //restricts the visibility of file names returned public class OnlyExt implements FilenameFilter { String ext; public OnlyExt(String ext) { this.ext = "." + ext; } public boolean accept(File dir, String name) { return name.endsWith(ext); } } 12 January 2014 Smitha N. Pai, CSE Dept. 35

36 // Directory of.HTML files. import java.io.*; //only display files with.html class DirListOnly { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); FilenameFilter only = new OnlyExt("html"); String s[] = f1.list(only); for (int i=0; i < s.length; i++) { System.out.println(s[i]); } } } 12 January 2014 Smitha N. Pai, CSE Dept. 36

37 The listFiles( ) Alternative File[ ] listFiles( ) File[ ] listFiles(FilenameFilter FFObj) File[ ] listFiles(FileFilter FObj) These methods return the file list as an array of File objects instead of strings. The first method returns all files, and the second returns those files that satisfy the specified FilenameFilter. The third version of listFiles( ) returns those files with path names that satisfy the specified FileFilter 12 January 2014 Smitha N. Pai, CSE Dept. 37

38 The listFiles( ) Alternative FileFilter defines only a single method, accept( ) which is called once for each file in a list. boolean accept(File path) The accept( ) method returns true for files that should be included in the list (that is, those that match the path argument), and false for those that should be excluded. 12 January 2014 Smitha N. Pai, CSE Dept. 38

39 Creating Directories File utility methods - mkdir( ) and mkdirs( ). The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. To create a directory for which no path exists, use the mkdirs( ) method. It creates both a directory and all the parents of the directory. 12 January 2014 Smitha N. Pai, CSE Dept. 39

40 The Stream Classes InputStream and OutputStream are designed for byte streams. Reader and Writer are designed for character streams. The byte stream classes and the character stream classes form separate hierarchies. Use the character stream classes when working with characters or strings, and use the byte stream classes when working with bytes or other binary objects. 12 January 2014 Smitha N. Pai, CSE Dept. 40

41 The Byte Streams The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte stream can be used with any type of object, including binary data. InputStream InputStream is an abstract class that defines Javas model of streaming byte input. All of the methods in this class will throw an IOException on error conditions. 12 January 2014 Smitha N. Pai, CSE Dept. 41

42 12 January 2014 Smitha N. Pai, CSE Dept. 42

43 OutputStream OutputStream is an abstract class that defines streaming byte output. All the methods in this class return a void value and throw an IOException in the case of errors. 12 January 2014 Smitha N. Pai, CSE Dept. 43

44 12 January 2014 Smitha N. Pai, CSE Dept. 44

45 FileInputStream The FileInputStream class creates an InputStream that you can use to read bytes from a file. FileInputStream(String filepath) FileInputStream(File fileObj) They can throw a FileNotFoundException. filepath is the full path name of a file, and fileObj is a File object that describes the file. FileInputStream f0 = new FileInputStream ("/autoexec.bat) File f = new File("/autoexec.bat"); FileInputStream f1 = new FileInputStream(f); 12 January 2014 Smitha N. Pai, CSE Dept. 45

46 FileInputStream FileInputStream is created, it is also opened for reading. FileInputStream overrides six of the methods in the abstract class InputStream. The mark( ) and reset( ) methods are not overridden, and any attempt to use reset( ) on a FileInputStream will generate an IOException. 12 January 2014 Smitha N. Pai, CSE Dept. 46

47 import java.io.*; class FileInputStreamDemo { public static void main(String args[]) throws Exception { int size; InputStream f =new FileInputStream("FileInputStreamDemo.java"); System.out.println("Total Available Bytes: " + (size = f.available())); int n = size/40; System.out.println("First " + n + " bytes of the file one read() at a time"); for (int i=0; i < n; i++) { System.out.print((char) f.read()); } 12 January 2014 Smitha N. Pai, CSE Dept. 47

48 System.out.println("\nStill Available: " + f.available()); System.out.println("Reading the next " + n + " with one read(b[])"); byte b[] = new byte[n]; if (f.read(b) != n) { System.err.println("couldn't read " + n + " bytes."); } System.out.println(new String(b, 0, n)); System.out.println("\nStill Available: " + (size = f.available())); System.out.println("Skipping half of remaining bytes with skip()"); f.skip(size/2); 12 January 2014 Smitha N. Pai, CSE Dept. 48

49 System.out.println("Still Available: " + f.available()); System.out.println("Reading " + n/2 + " into the end of array"); if (f.read(b, n/2, n/2) != n/2) { System.err.println("couldn't read " + n/2 + " bytes."); } System.out.println(new String(b, 0, b.length)); System.out.println("\nStill Available: " + f.available()); f.close(); } 12 January 2014 Smitha N. Pai, CSE Dept. 49

50 Here is the output produced by this program: Total Available Bytes: 1433 First 35 bytes of the file one read() at a time // Demonstrate FileInputStream. im Still Available: 1398 Reading the next 35 with one read(b[]) port java.io.*; class FileInputS Still Available: 1363 Skipping half of remaining bytes with skip() Still Available: 682 Reading 17 into the end of array port java.io.*; read(b) != n) { S Still Available: 665 12 January 2014 Smitha N. Pai, CSE Dept. 50

51 FileOutputStream FileOutputStream creates an OutputStream that you can use to write bytes to a file. FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append) They can throw a FileNotFoundException or a SecurityException. filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, the file is opened in append mode. 12 January 2014 Smitha N. Pai, CSE Dept. 51

52 Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will create the file before opening it for output when you create the object. In the case where you attempt to open a read- only file, an IOException will be thrown. 12 January 2014 Smitha N. Pai, CSE Dept. 52

53 // Demonstrate FileOutputStream. import java.io.*; class FileOutputStreamDemo { public static void main(String args[]) throws Exception { String source = "Now is the time for all good men\n" + " to come to the aid of their country\n" + " and pay their due taxes."; byte buf[] = source.getBytes(); OutputStream f0 = new FileOutputStream("file1.txt"); for (int i=0; i < buf.length; i += 2) { f0.write(buf[i]); } f0.close(); 12 January 2014 Smitha N. Pai, CSE Dept. 53

54 OutputStream f1 = new FileOutputStream("file2.txt"); f1.write(buf); f1.close(); OutputStream f2 = new FileOutputStream("file3.txt"); f2.write(buf,buf.length-buf.length/4,buf.length/4); f2.close(); } } //output First, file1.txt: Nwi h iefralgo e t oet h i ftercuty n a hi u ae. Next, file2.txt: Now is the time for all good men to come to the aid of their country and pay their due taxes. Finally, file3.txt: nd pay their due taxes. 12 January 2014 Smitha N. Pai, CSE Dept. 54

55 /* Display a text file. To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile TEST.TXT */ import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; 12 January 2014 Smitha N. Pai, CSE Dept. 55

56 try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File Not Found"); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: ShowFile File"); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); } 12 January 2014 Smitha N. Pai, CSE Dept. 56

57 /* Copy a text file. To use this program, specify the name of the source file and the destination file. For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, use the following command line. java CopyFile FIRST.TXT SECOND.TXT */ 12 January 2014 Smitha N. Pai, CSE Dept. 57

58 import java.io.*; class CopyFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; FileOutputStream fout; try { // open input file try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("Input File Not Found"); return; } 12 January 2014 Smitha N. Pai, CSE Dept. 58

59 // open output file try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException e) { System.out.println("Error Opening Output File"); return; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: CopyFile From To"); return; } 12 January 2014 Smitha N. Pai, CSE Dept. 59

60 // Copy File try { do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("File Error"); } fin.close(); fout.close(); } 12 January 2014 Smitha N. Pai, CSE Dept. 60

61 SequenceInputStream The SequenceInputStream class allows you to concatenate multiple InputStreams. A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of InputStreams as its argument: SequenceInputStream(InputStream first, InputStream second) SequenceInputStream(Enumeration streamEnum) Operationally, the class fulfills read requests from the first InputStream until it runs out and then switches over to the second one 12 January 2014 Smitha N. Pai, CSE Dept. 61

62 SequenceInputStream In the case of an Enumeration, it will continue through all of the InputStreams until the end of the last one is reached. 12 January 2014 Smitha N. Pai, CSE Dept. 62

63 // Demonstrate sequenced input. import java.io.*; import java.util.*; class InputStreamEnumerator implements Enumeration { private Enumeration files; public InputStreamEnumerator(Vector files) { this.files = files.elements(); } public boolean hasMoreElements() { return files.hasMoreElements(); } public Object nextElement() { try { return new FileInputStream(files.nextElement().toString()); } catch (Exception e) { return null; } } } 12 January 2014 Smitha N. Pai, CSE Dept. 63

64 class SequenceInputStreamDemo { public static void main(String args[]) throws Exception { int c; Vector files = new Vector(); files.addElement("/autoexec.bat"); files.addElement("/config.sys"); InputStreamEnumerator e = new InputStreamEnumerator(files); InputStream input = new SequenceInputStream(e); while ((c = input.read()) != -1) { System.out.print((char) c); } input.close(); } 12 January 2014 Smitha N. Pai, CSE Dept. 64

65 PrintStream The PrintStream class provides all of the formatting capabilities we have been using from the System file handle, System.out PrintStream(OutputStream outputStream) PrintStream(OutputStream outputStream, boolean flushOnNewline) where flushOnNewline controls whether Java flushes the output stream every time a newline (\n) character is output. 12 January 2014 Smitha N. Pai, CSE Dept. 65

66 PrintStream If flushOnNewline is true, flushing automatically takes place. If it is false, flushing is not automatic. The first constructor does not automatically flush. Javas PrintStream objects support the print( ) and println( ) methods for all types, including Object. If an argument is not a simple type, the PrintStream methods will call the objects toString( ) method and then print the result. 12 January 2014 Smitha N. Pai, CSE Dept. 66

67 The PrintWriter Class To write to the console use PrintWriter stream. PrintWriter is one of the character-based classes. PrintWriter(OutputStream outputStream, boolean flushOnNewline) outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewline is true, flushing automatically takes place else if false, flushing is not automatic. 12 January 2014 Smitha N. Pai, CSE Dept. 67

68 PrintWriter supports the print( ) and println( ) methods for all types including Object. If an argument is not a simple type, the PrintWriter methods call the objects toString( ) method and then print the result. To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. PrintWriter pw = new PrintWriter(System.out, true); 12 January 2014 Smitha N. Pai, CSE Dept. 68

69 // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } The output from this program is shown here: This is a string -7 4.5E-7 12 January 2014 Smitha N. Pai, CSE Dept. 69

70 Writing Console Output PrintStream is an output stream derived from OutputStream It implements the low-level method write( ). write( ) can be used to write to the console. void write(int byteval) This method writes to the stream the byte specified by byteval. byteval is declared as an integer and only the low-order eight bits are written 12 January 2014 Smitha N. Pai, CSE Dept. 70

71 RandomAccessFile RandomAccessFile encapsulates a random-access file. It implements the interfaces DataInput and DataOutput, which define the basic I/O methods. It supports positioning requests you can position the file pointer within the file. RandomAccessFile(File fileObj, String access) throws FileNotFoundException RandomAccessFile(String filename, String access) throws FileNotFoundException 12 January 2014 Smitha N. Pai, CSE Dept. 71

72 access determines what type of file access is permitted. If it is r, then the file can be read, but not written. If it is rw, then the file is opened in read-write mode. If it is rws, the file is opened for read-write operations and every change to the files data or metadata will be immediately written to the physical device. If it is rwd, the file is opened for read-write operations and every change to the files data will be immediately written to the physical device. 12 January 2014 Smitha N. Pai, CSE Dept. 72

73 The method seek( ), shown here, is used to set the current position of the file pointer within the file: void seek(long newPos) throws IOException newPos specifies the new position, in bytes, of the file pointer from the beginning of the file. After a call to seek( ), the next read or write operation will occur at the new file position. 12 January 2014 Smitha N. Pai, CSE Dept. 73

74 RandomAccessFile implements the standard input and output methods, which you can use to read and write to random access files. setLength( ) void setLength(long len) throws IOException This method sets the length of the invoking file to that specified by len. This method can be used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined. 12 January 2014 Smitha N. Pai, CSE Dept. 74

75 The Character Streams Reader Reader is an abstract class that defines Javas model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Writer Writer is an abstract class that defines streaming character output. All of the methods in this class return a void value and throw an IOException in the case of errors. 12 January 2014 Smitha N. Pai, CSE Dept. 75

76 The Character Streams FileReader The FileReader class creates a Reader that you can use to read the contents of a file. Two forms: FileReader(String filePath) FileReader(File fileObj) Methods defined by reader and writer classes follows 12 January 2014 Smitha N. Pai, CSE Dept. 76

77 12 January 2014 Smitha N. Pai, CSE Dept. 77

78 12 January 2014 Smitha N. Pai, CSE Dept. 78

79 // Demonstrate FileReader. import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } 12 January 2014 Smitha N. Pai, CSE Dept. 79

80 FileWriter FileWriter creates a Writer that you can use to write to a file. FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append) They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file. 12 January 2014 Smitha N. Pai, CSE Dept. 80

81 FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown. 12 January 2014 Smitha N. Pai, CSE Dept. 81

82 // Demonstrate FileWriter. import java.io.*; class FileWriterDemo { public static void main(String args[]) throws Exception { String source = "Now is the time for all good men\n" + " to come to the aid of their country\n" + " and pay their due taxes."; char buffer[] = new char[source.length()]; source.getChars(0, source.length(), buffer, 0); FileWriter f0 = new FileWriter("file1.txt"); for (int i=0; i < buffer.length; i += 2) { f0.write(buffer[i]); } f0.close(); 12 January 2014 Smitha N. Pai, CSE Dept. 82

83 FileWriter f1 = new FileWriter("file2.txt"); f1.write(buffer); f1.close(); FileWriter f2 = new FileWriter("file3.txt"); f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4); f2.close(); } } First, file1.txt: Nwi h iefralgo e t oet h i ftercuty n a hi u ae. Next, file2.txt: Now is the time for all good men to come to the aid of their country and pay their due taxes. Finally, file3.txt: nd pay their due taxes 12 January 2014 Smitha N. Pai, CSE Dept. 83

84 CharArrayReader CharArrayReader is an implementation of an input stream that uses a character array as the source. CharArrayReader(char array[ ]) CharArrayReader(char array[ ], int start, int numChars) Here, array is the input source. 12 January 2014 Smitha N. Pai, CSE Dept. 84

85 // Demonstrate CharArrayReader. import java.io.*; public class CharArrayReaderDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); 12 January 2014 Smitha N. Pai, CSE Dept. 85

86 int i; System.out.println("input1 is:"); while((i = input1.read()) != -1) { System.out.print((char)i); } System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1) { System.out.print((char)i); } System.out.println(); } } input1 is: abcdefghijklmnopqrstuvwxyz input2 is: abcde 12 January 2014 Smitha N. Pai, CSE Dept. 86

87 CharArrayWriter CharArrayWriter is an implementation of an output stream that uses an array as the destination. CharArrayWriter( ) CharArrayWriter(int numChars) The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if needed. The number of characters held by the buffer is contained in the count field of CharArrayWriter. Both buf and count are protected fields. 12 January 2014 Smitha N. Pai, CSE Dept. 87

88 // Demonstrate CharArrayWriter. import java.io.*; class CharArrayWriterDemo { public static void main(String args[]) throws IOException { CharArrayWriter f = new CharArrayWriter(); String s = "This should end up in the array"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); f.write(buf); System.out.println("Buffer as a string"); System.out.println(f.toString()); System.out.println("Into array"); char c[] = f.toCharArray(); 12 January 2014 Smitha N. Pai, CSE Dept. 88

89 for (int i=0; i<c.length; i++) { System.out.print(c[i]); } System.out.println("\nTo a FileWriter()"); FileWriter f2 = new FileWriter("test.txt"); f.writeTo(f2); f2.close(); System.out.println("Doing a reset"); f.reset(); for (int i=0; i<3; i++) f.write('X'); System.out.println(f.toString()); } 12 January 2014 Smitha N. Pai, CSE Dept. 89

90 12 January 2014 Smitha N. Pai, CSE Dept. 90 Buffer as a string This should end up in the array Into array This should end up in the array To a FileWriter() Doing a reset XXX

91 BufferedReader BufferedReader improves performance by buffering input. BufferedReader(Reader inputStream) BufferedReader(Reader inputStream, int bufSize) 12 January 2014 Smitha N. Pai, CSE Dept. 91

92 // Use buffered input. import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws IOException { String s = "This is a © copyright symbol " + "but this is &copy not.\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); CharArrayReader in = new CharArrayReader(buf); BufferedReader f = new BufferedReader(in); int c; 12 January 2014 Smitha N. Pai, CSE Dept. 92

93 boolean marked = false; while ((c = f.read()) != -1) { switch(c) { case '&': if (!marked) { f.mark(32); marked = true; } else { marked = false; } break; case ';': if (marked) { marked = false; System.out.print("(c)"); } else System.out.print((char) c); break; 12 January 2014 Smitha N. Pai, CSE Dept. 93

94 case ' ': if (marked) { marked = false; f.reset(); System.out.print("&"); } else System.out.print((char) c); break; default: if (!marked) System.out.print((char) c); break; } Output: This is a (c) copyright symbol but this is &copy not. 12 January 2014 Smitha N. Pai, CSE Dept. 94

95 BufferedWriter A BufferedWriter is a Writer that adds a flush( ) method that can be used to ensure that data buffers are physically written to the actual output stream. BufferedWriter can increase performance by reducing the number of times data is actually physically written to the output stream. BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream, int bufSize) The first form creates a buffered stream using a buffer with a default size. 12 January 2014 Smitha N. Pai, CSE Dept. 95

96 PrintWriter PrintWriter is essentially a character-oriented version of PrintStream. It provides the formatted output methods print( ) and println( ). PrintWriter(OutputStream outputStream) PrintWriter(OutputStream outputStream, boolean flushOnNewline) PrintWriter(Writer outputStream) PrintWriter(Writer outputStream, boolean flushOnNewline) where flushOnNewline controls whether Java flushes the output stream every time println( ) is called. 12 January 2014 Smitha N. Pai, CSE Dept. 96

97 PrintWriter If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic. Javas PrintWriter objects support the print( ) and println( ) methods for all types, including Object. If an argument is not a simple type, the PrintWriter methods will call the objects toString( ) method and then print out the result. 12 January 2014 Smitha N. Pai, CSE Dept. 97

98 Using Stream I/O // A word counting utility. import java.io.*; class WordCount { public static int words = 0; public static int lines = 0; public static int chars = 0; public static void wc(InputStreamReader isr) throws IOException { int c = 0; boolean lastWhite = true; 12 January 2014 Smitha N. Pai, CSE Dept. 98

99 String whiteSpace = " \t\n\r"; while ((c = isr.read()) != -1) { // Count characters chars++; // Count lines if (c == '\n') { lines++; } 12 January 2014 Smitha N. Pai, CSE Dept. 99

100 // Count words by detecting the start of a word int index = whiteSpace.indexOf(c); if(index == -1) { if(lastWhite == true) { ++words; } lastWhite = false; } else { lastWhite = true; } if(chars != 0) { ++lines; } 12 January 2014 Smitha N. Pai, CSE Dept. 100

101 public static void main(String args[]) { FileReader fr; try { if (args.length == 0) { // We're working with stdin wc(new InputStreamReader(System.in)); } else { // We're working with a list of files for (int i = 0; i < args.length; i++) { fr = new FileReader(args[i]); wc(fr); } catch (IOException e) { return; } System.out.println(lines + " " + words + " " + chars); } } 12 January 2014 Smitha N. Pai, CSE Dept. 101

102 The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. 12 January 2014 Smitha N. Pai, CSE Dept. 102 Improving wc( ) Using a StreamTokenizer

103 StreamTokenizer breaks up the InputStream into tokens that are delimited by sets of characters. StreamTokenizer(Reader inStream) inStream must be some form of Reader. To reset the default set of delimiters, we will employ the resetSyntax( ) method – Removes delimiters The default set of delimiters is finely tuned for tokenizing Java programs Tokens, or words, are any consecutive string of visible characters delimited on both sides by whitespace. 12 January 2014 Smitha N. Pai, CSE Dept. 103

104 A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF. 12 January 2014 Smitha N. Pai, CSE Dept. 104

105 double nval If the current token is a number, this field contains the value of that number.nval String sval If the current token is a word token, this field contains a string giving the characters of the word token.Stringsval static int TT_EOF A constant indicating that the end of the stream has been read.TT_EOF static int TT_EOL A constant indicating that the end of the line has been read.TT_EOL 12 January 2014 Smitha N. Pai, CSE Dept. 105

106 static int TT_NUMBER A constant indicating that a number token has been read.TT_NUMBER static int TT_WORD A constant indicating that a word token has been read.TT_WORD int ttype After a call to the nextToken method, this field contains the type of the token just read.ttype 12 January 2014 Smitha N. Pai, CSE Dept. 106

107 public int ttype For a single character token, its value is the single character, converted to an integer. For a quoted string token its value is the quote character. Otherwise, its value is one of the following: TT_WORD indicates that the token is a word. TT_NUMBER indicates that the token is a number. TT_EOL indicates that the end of line has been read. The field can only have this value if the eolIsSignificant() method has been called with the argument true. TT_EOF indicates that the end of the input stream has been reached. 12 January 2014 Smitha N. Pai, CSE Dept. 107

108 the eolIsSignificant( ) method to ensure that newline characters will be delivered as tokens, so we can count the number of lines as well as words. void eolIsSignificant(boolean eolFlag) If eolFlag is true, the end-of-line characters are returned as tokens. If eolFlag is false, the end-of-line characters are ignored. The wordChars( ) method is used to specify the range of characters that can be used in words. void wordChars(int start, int end) start and end specify the range of valid characters. 12 January 2014 Smitha N. Pai, CSE Dept. 108

109 The whitespace characters are specified using whitespaceChars( ). void whitespaceChars(int start, int end) start and end specify the range of valid whitespace characters. The next token is obtained from the input stream by calling nextToken( ). StreamTokenizer defines four int constants: TT_EOF, TT_EOL, TT_NUMBER, and TT_WORD. 12 January 2014 Smitha N. Pai, CSE Dept. 109

110 ttype is a public int indicating the type of token that has just been read by the nextToken( ) method. If the token is a word, ttype equals TT_WORD. If the token is a number, ttype equals TT_NUMBER. If the token is a single character, ttype contains its value. If an end-of-line condition has been encountered, ttype equals TT_EOL If the end of the stream has been encountered, ttype equals TT_EOF. 12 January 2014 Smitha N. Pai, CSE Dept. 110

111 // Enhanced word count program that uses a StreamTokenizer import java.io.*; class WordCount { public static int words=0; public static int lines=0; public static int chars=0; public static void wc(Reader r) throws IOException { StreamTokenizer tok = new StreamTokenizer(r); tok.resetSyntax(); //Resets this tokenizer's syntax table so that all characters are "ordinary. It removes any special significance the character has as a comment character string delimiter, white space, or number character. The parser treates it as a single-character token and sets ttype field to the character value. tok.wordChars(33, 255);// Specifies that all characters c in the range low <= c <= high are word constituents. 12 January 2014 Smitha N. Pai, CSE Dept. 111

112 tok.whitespaceChars(0, ' ');//Specifies that all characters c in the range low <= c <= high are white space characters. tok.eolIsSignificant(true);// Determines whether or not ends of line are treated as tokens. while (tok.nextToken() != tok.TT_EOF) { switch (tok.ttype) { case StreamTokenizer.TT_EOL: lines++; chars++; break; case StreamTokenizer.TT_WORD: words++; 12 January 2014 Smitha N. Pai, CSE Dept. 112

113 default: // FALLSTHROUGH chars += tok.sval.length(); break; //If the current token is a word token, this field contains a string giving the characters of the word token. When the current token is a quoted string token, this field contains the body of the string. The current token is a word when the value of the ttype field is TT_WORD. The current token is a quoted string token when the value of the ttype field is a quote character. } } } 12 January 2014 Smitha N. Pai, CSE Dept. 113

114 public static void main(String args[]) { if (args.length == 0) { // We're working with stdin try { wc(new InputStreamReader(System.in)); System.out.println(lines + " " + words + " " + chars); } catch (IOException e) {}; } else { // We're working with a list of files int twords = 0, tchars = 0, tlines = 0; for (int i=0; i<args.length; i++) { try { words = chars = lines = 0; wc(new FileReader(args[i])); twords += words; tchars += chars; tlines += lines; System.out.println(args[i] + ": " + lines + " " + words + " " + chars); } 12 January 2014 Smitha N. Pai, CSE Dept. 114

115 catch (IOException e) { System.out.println(args[i] + ": error."); } System.out.println("total: " + tlines + " " + twords + " " + tchars); } 12 January 2014 Smitha N. Pai, CSE Dept. 115

116 Serialization Serialization is the process of writing the state of an object to a byte stream. This is useful when you want to save the state of your program to a persistent storage area, such as a file. Serialization is also needed to implement Remote Method Invocation (RMI). 12 January 2014 Smitha N. Pai, CSE Dept. 116

117 Serialization RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. An object may be supplied as an argument to that remote method. The sending machine serializes the object and transmits it. The receiving machine deserializes it. 12 January 2014 Smitha N. Pai, CSE Dept. 117

118 Objects may also contain references to themselves. Similarly, during the process of deserialization, all of these objects and their references are correctly restored. 12 January 2014 Smitha N. Pai, CSE Dept. 118

119 Serializable Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable. Variables that are declared as transient are not saved by the serialization facilities. Also, static variables are not saved. 12 January 2014 Smitha N. Pai, CSE Dept. 119

120 Externalizable It may be desirable to use compression or encryption techniques. The Externalizable interface is designed for these situations. The Externalizable interface defines these two methods: void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundException void writeExternal(ObjectOutput outStream) throws IOException 12 January 2014 Smitha N. Pai, CSE Dept. 120

121 Externalizable inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written. 12 January 2014 Smitha N. Pai, CSE Dept. 121

122 ObjectOutput The ObjectOutput interface extends the DataOutput interface and supports object Serialization All of these methods will throw an IOException on error conditions. 12 January 2014 Smitha N. Pai, CSE Dept. 122

123 12 January 2014 Smitha N. Pai, CSE Dept. 123

124 ObjectInputStream The ObjectInputStream class extends the InputStream class and implements the ObjectInput interface. ObjectInputStream is responsible for reading objects from a stream. ObjectInputStream(InputStream inStream) throws IOException, StreamCorruptedException inStream is the input stream from which serialized objects should be read. 12 January 2014 Smitha N. Pai, CSE Dept. 124

125 12 January 2014 Smitha N. Pai, CSE Dept. 125

126 12 January 2014 Smitha N. Pai, CSE Dept. 126

127 A Serialization Example import java.io.*; public class SerializationDemo { public static void main(String args[]) { // Object serialization try { MyClass object1 = new MyClass("Hello", -7, 2.7e10); System.out.println("object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(Exception e) { System.out.println("Exception during serialization: " + e); System.exit(0); } 12 January 2014 Smitha N. Pai, CSE Dept. 127

128 12 January 2014 Smitha N. Pai, CSE Dept. 128 // Object deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) { System.out.println("Exception during deserialization: " + e); System.exit(0); }

129 class MyClass implements Serializable { String s; int i; double d; public MyClass(String s, int i, double d) { this.s = s; this.i = i; this.d = d; } public String toString() { return "s=" + s + "; i=" + i + "; d=" + d; } This program demonstrates that the instance variables of object1 and object2 are identical. The output is shown here: object1: s=Hello; i=-7; d=2.7E10 object2: s=Hello; i=-7; d=2.7E10 12 January 2014 Smitha N. Pai, CSE Dept. 129

130 Stream Benefits The streaming interface to I/O in Java provides a clean abstraction for a complex task. The composition of the filtered stream classes allows to dynamically build the custom streaming interface to suit data transfer requirements. Java programs written to adhere to the abstract, high-level InputStream, OutputStream, Reader, and Writer classes will function properly in the future even when new and improved concrete stream classes are invented. 12 January 2014 Smitha N. Pai, CSE Dept. 130


Download ppt "I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1."

Similar presentations


Ads by Google