Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java I/O L. Grewe. Overview of java.io methods for accessing file, text data, object serialization and internationalization methods for accessing file,

Similar presentations


Presentation on theme: "Java I/O L. Grewe. Overview of java.io methods for accessing file, text data, object serialization and internationalization methods for accessing file,"— Presentation transcript:

1 Java I/O L. Grewe

2 Overview of java.io methods for accessing file, text data, object serialization and internationalization methods for accessing file, text data, object serialization and internationalization Sequential and Random access Sequential and Random access Reading and writing of primitive values Reading and writing of primitive values Applications and applets are provided with three streams automatically Applications and applets are provided with three streams automatically System.out (output stream) System.out (output stream) System.in (input stream) System.in (input stream) System.err (error stream System.err (error stream

3 Uses Streams Two kinds of basic streams: Two kinds of basic streams: 1. byte based streams 8 bits, data-based 8 bits, data-based input streams and output streams input streams and output streams 2. character based streams 16 bits, text-based 16 bits, text-based readers and writers readers and writers

4 Byte Streams Two parent abstract classes: InputStream and OutputStream Two parent abstract classes: InputStream and OutputStream Reading bytes: Reading bytes: InputStream class defines an abstract methodInputStream class defines an abstract method public abstract int read() throws IOException Designer of a concrete input stream class overrides this method to provide useful functionality. Designer of a concrete input stream class overrides this method to provide useful functionality. E.g. in the FileInputStream class, the method reads one byte from a file E.g. in the FileInputStream class, the method reads one byte from a file InputStream class also contains nonabstract methods to read an array of bytes or skip a number of bytesInputStream class also contains nonabstract methods to read an array of bytes or skip a number of bytes Writing bytes : Writing bytes : OutputStream class defines an abstract methodOutputStream class defines an abstract method public abstract void write(int b) throws IOException OutputStream class also contains nonabstract methods for tasks such as writing bytes from a specified byte arrayOutputStream class also contains nonabstract methods for tasks such as writing bytes from a specified byte array Close the stream after reading of writing to it to free up limited operating system resources by using close() Close the stream after reading of writing to it to free up limited operating system resources by using close()

5 Byte Streams (Binary Streams)…some of the hierarchy Object InputStream FileInputStream FilterInputStream BufferedInputStream FilterOutputStream FileOutputStream BufferedOutputStream DataInputStream OutputStream DataOutputStream PrintStream

6 Byte Stream some of the hierarchy InputStream AutioInputStream FileInputStream ObjectInputStream SequenceInputStream ByteArrayInputStream PipedInputStream FilterInputStream

7 Java Programming Byte Streams OutputStream FileOutputStream ObjectOutputStream ByteArrayOutputStream PipeOutputStream FilterOutputStream

8 Byte Streams import java.io.*; public class CountBytes { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { InputStream in; InputStream in; if (args.length == 0) if (args.length == 0) in = System.in; in = System.in; else else in = new FileInputStream(args[0]); in = new FileInputStream(args[0]); int total = 0; int total = 0; while (in.read() != -1) while (in.read() != -1) total++; total++; System.out.println(total + " bytes"); System.out.println(total + " bytes"); }} The abstract class InputStream declares methods to read bytes from a particular source. Reads a single byte of data and returns the byte that was read, as an integer in the range 0 to 255, not -128 to 127(unsigned). Type is InputStream

9 Example code1: import java.io.*; class CountBytes { public static void main(String[] args) throws IOException { FileInputStream in = new FileInputStream(args[0]); FileInputStream in = new FileInputStream(args[0]); int total = 0; int total = 0; while (in.read() != -1) while (in.read() != -1) total++; total++; in.close(); in.close(); System.out.println(total + ” bytes”); System.out.println(total + ” bytes”);}} Example code2: import java.io.*; class TranslateByte { public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException { byte from = (byte)args[0].charAt(0); byte from = (byte)args[0].charAt(0); byte to = (byte)args[1].charAt(0); byte to = (byte)args[1].charAt(0); int x; int x; while((x = System.in.read()) != -1) while((x = System.in.read()) != -1) System.out.write(x == from ? to : x); System.out.write(x == from ? to : x); }} If you run “java TranslateByte b B” and enter text bigboy via the keyboard the output will be: BigBoy!

10 Byte Stream - output

11 Byte Stream - Output import java.io.*; public class TranslateByte { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { byte from = (byte) args[0].charAt(0); byte from = (byte) args[0].charAt(0); byte to = (byte) args[1].charAt(0); byte to = (byte) args[1].charAt(0); int b; int b; while ((b = System.in.read()) != -1) while ((b = System.in.read()) != -1) System.out.write(b == from ? to : b); System.out.write(b == from ? to : b); }} The abstract class OutputStream provides an abstraction for writing bytes to a destination. Run: Java TranslateByte b B Result: (input  abracadabra!) aBracadaBra! Type is PrintStream

12 Character streams Two parent abstract classes for characters: Reader and Writer. Each support similar methods to those of its byte stream counterpart –InputStream and OutputStream, respectively Two parent abstract classes for characters: Reader and Writer. Each support similar methods to those of its byte stream counterpart –InputStream and OutputStream, respectively The standard streams— System.in, System.out and System.err —existed before the invention of character streams. So they are byte streams though logically they should be character streams. The standard streams— System.in, System.out and System.err —existed before the invention of character streams. So they are byte streams though logically they should be character streams.

13 Character Streams - Reading Reader BufferedReader InputStreamReader StringReader CharArrayReader PipedReader FilterReader

14 Character Streams - Writing Writer BufferedWriter OutputStreamWriter StringWriter CharArrayWriter PipedWriter FilterWriter PrintWriter

15 Conversion between byte and character streams The conversion streams InputStreamReader and OutputStreamReader translate between Character and byte streams The conversion streams InputStreamReader and OutputStreamReader translate between Character and byte streams public InputStreamReader(InputStream in)public InputStreamReader(InputStream in) public InputStreamReader(InputStream in, String encoding)public InputStreamReader(InputStream in, String encoding) public OutputStreamWriter(OutputStream out)public OutputStreamWriter(OutputStream out) public OutputStreamWriter(OutputStream out, String encoding)public OutputStreamWriter(OutputStream out, String encoding) read method of InputStreamReader read bytes from their associated InputStream and convert them to characters using the appropriate encoding for that stream read method of InputStreamReader read bytes from their associated InputStream and convert them to characters using the appropriate encoding for that stream write method of OutputStreamWriter take the supplied characters, convert them to bytes using the appropriate encoding and write them to its associated OutputStream write method of OutputStreamWriter take the supplied characters, convert them to bytes using the appropriate encoding and write them to its associated OutputStream Closing the conversion stream also closes the associated byte stream – may not always desirable Closing the conversion stream also closes the associated byte stream – may not always desirable

16 Character Stream Example import java.io.*; public class CountSpace { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { Reader in; Reader in; if (args.length == 0) if (args.length == 0) in = new InputStreamReader(System.in); in = new InputStreamReader(System.in); else else in = new FileReader(args[0]); in = new FileReader(args[0]); int ch; int ch; int total; int total; int spaces = 0; int spaces = 0; for (total = 0; (ch = in.read()) != -1; total++) { for (total = 0; (ch = in.read()) != -1; total++) { if (Character.isWhitespace((char) ch)) if (Character.isWhitespace((char) ch)) spaces++; spaces++; } System.out.println(total + " chars " System.out.println(total + " chars " + spaces + " spaces"); + spaces + " spaces"); }} The abstract classes for reading and writing streams of characters are Reader and Writer. Run: Java CountSpace CountSpace.java Result: 520 characters 172 spaces The abstract class Reader provides a character stream analogous to the byte stream InputStream and the methods of Reader essentially mirror those of InputStream. The conversion streams InputStreamReader and OutputStreamWriter translate between character and byte streams using either a specified character set encoding or the default encoding for the local system.

17 Reading from a Stream The basic read() method reads a byte at a time. The basic read() method reads a byte at a time. Some other methods that read more than 1 byte Some other methods that read more than 1 byte public int read(byte[] data) throws IOExceptionpublic int read(byte[] data) throws IOException Tries to read enough bytes to fill the array data Tries to read enough bytes to fill the array data public int read(byte[] data, int offset, int length) throws IOExceptionpublic int read(byte[] data, int offset, int length) throws IOException Tries to read length bytes from stream and store in data[] at starting index offset Tries to read length bytes from stream and store in data[] at starting index offset These methods then return the number of bytes actually read. You should not assume that the array will be filled or that length bytes will actually have been read. If the end of stream is encountered, -1 is returnedThese methods then return the number of bytes actually read. You should not assume that the array will be filled or that length bytes will actually have been read. If the end of stream is encountered, -1 is returned

18 Reading Use other classes with richer methods (i.e. DataInputStream) to read in different data types Use other classes with richer methods (i.e. DataInputStream) to read in different data types

19 Writing abstract void write(char[] cbuf, int off, int len) Write a portion of an array of characters. abstract void write(char[] cbuf, int off, int len) Write a portion of an array of characters. write void write(int c) Write a single character. voidwrite(String str) Write a string. voidwrite(String str, int off, int len) Write a portion of a string. void write(int c) Write a single character. voidwrite(String str) Write a string. voidwrite(String str, int off, int len) Write a portion of a string.write StringwriteStringwrite StringwriteString Other methods – for byte based – print*(*) Other methods – for byte based – print*(*) abstract void close() Close the stream, flushing it abstract void close() Close the stream, flushing itclose abstract void flush() Flush the stream. voidwrite(char[] cbuf) Write an array of characters. abstract void flush() Flush the stream. voidwrite(char[] cbuf) Write an array of characters.flushwriteflushwrite

20 File I/O : The File class The File class is particularly useful for retrieving information about a file or a directory from a disk. The File class is particularly useful for retrieving information about a file or a directory from a disk. A File object actually represents a path, not necessarily an underlying fileA File object actually represents a path, not necessarily an underlying file A File object doesn’t open files or provide any file-processing capabilitiesA File object doesn’t open files or provide any file-processing capabilities Three constructors Three constructors public File( String name) public File( String name) public File( String pathToName, String name) public File( String pathToName, String name) public File( File directory, String name) public File( File directory, String name) Main methods Main methods boolean canRead() / boolean canWrite()boolean canRead() / boolean canWrite() boolean exists()boolean exists() boolean isFile() / boolean isDirectory() / boolean isAbsolute()boolean isFile() / boolean isDirectory() / boolean isAbsolute() String getAbsolutePath() / String getPath()String getAbsolutePath() / String getPath() String getParent()String getParent() String getName()String getName() long length()long length() long lastModified()long lastModified()

21 File I/O Sequential-Access file: the File streams— FileInputStream, FileOutputStream, FileReader and FileWriter —allow you to treat a file as a stream to input or output sequentially Sequential-Access file: the File streams— FileInputStream, FileOutputStream, FileReader and FileWriter —allow you to treat a file as a stream to input or output sequentially Each file stream type has three types of constructorsEach file stream type has three types of constructors A constructor that takes a String which is the name of the file A constructor that takes a String which is the name of the file A constructor that take a File object which refers to the file A constructor that take a File object which refers to the file A constructor that takes a FileDescriptor object A constructor that takes a FileDescriptor object Random-Access file: RandomAccessFile allow you to read/write data beginning at the a specified location Random-Access file: RandomAccessFile allow you to read/write data beginning at the a specified location a file pointer is used to guide the starting positiona file pointer is used to guide the starting position It’s not a subclass of InputStream, OutputStream, Reader or Writer because it supports both input and output with both bytes and charactersIt’s not a subclass of InputStream, OutputStream, Reader or Writer because it supports both input and output with both bytes and characters

22 Example of RandomAccessFile import java.io.*; class Filecopy { public static void main(String args[]) { public static void main(String args[]) { RandomAccessFile fh1 = null; RandomAccessFile fh1 = null; RandomAccessFile fh2 = null; RandomAccessFile fh2 = null; long filesize = -1; long filesize = -1; byte[] buffer1; byte[] buffer1; try { try { fh1 = new RandomAccessFile(args[0], “r”); fh1 = new RandomAccessFile(args[0], “r”); fh2 = new RandomAccessFile(args[1], “rw”); fh2 = new RandomAccessFile(args[1], “rw”); } catch (FileNotFoundException e) { } catch (FileNotFoundException e) { System.out.println(“File not found”); System.out.println(“File not found”); System.exit(100); System.exit(100); } try { try { filesize = fh1.length(); filesize = fh1.length(); int bufsize = (int)filesize/2; int bufsize = (int)filesize/2; buffer1 = new byte[bufsize]; buffer1 = new byte[bufsize]; fh1.readFully(buffer1, 0, bufsize); fh1.readFully(buffer1, 0, bufsize); fh2.write(buffer1, 0, bufsize); fh2.write(buffer1, 0, bufsize); } catch (IOException e) { } catch (IOException e) { System.out.println("IO error occurred!"); System.out.println("IO error occurred!"); System.exit(200); System.exit(200); } }}

23 Add more efficiency BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. BufferedReader (Reader in) For example: For example:  to wrap an InputStreamReader inside a BufferedReader BufferedReader in BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); = new BufferedReader(new InputStreamReader(System.in));  to wrap a FileReader inside a BufferedReader  to wrap a FileReader inside a BufferedReader BufferedReader in BufferedReader in = new BufferedReader(new FileReader(“fileName”)); = new BufferedReader(new FileReader(“fileName”)); then you can invoke in.readLine() to read from the file line by line then you can invoke in.readLine() to read from the file line by line

24 import java.io.*; public class EfficientReader { public static void main (String[] args) { public static void main (String[] args) { try { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); BufferedReader br = new BufferedReader(new FileReader(args[0])); // get line // get line String line = br.readLine(); String line = br.readLine(); // while not end of file… keep reading and displaying lines // while not end of file… keep reading and displaying lines while (line != null) { while (line != null) { System.out.println("Read a line:"); System.out.println("Read a line:"); System.out.println(line); System.out.println(line); line = br.readLine(); line = br.readLine(); } // close stream // close stream br.close(); br.close(); } catch(FileNotFoundException fe) { } catch(FileNotFoundException fe) { System.out.println("File not found: “+ args[0]"); System.out.println("File not found: “+ args[0]"); } catch(IOException ioe) { } catch(IOException ioe) { System.out.println("Can’t read from file: “+args[0]); System.out.println("Can’t read from file: “+args[0]); } }}

25 Buffering Improves performance of I/O Improves performance of I/O Copies each output to a region of memory called a buffer Copies each output to a region of memory called a buffer Entire buffer output to disk at once Entire buffer output to disk at once One long disk access takes less time than many smaller ones One long disk access takes less time than many smaller ones BufferedInputStream buffers file outputBufferedInputStream buffers file output BufferedOutputStream buffers file inputBufferedOutputStream buffers file input

26 Appending to a File To append to file instead of overwriting it pass the boolean value true as the second argument to the FileOutputStream() constructor. For example, To append to file instead of overwriting it pass the boolean value true as the second argument to the FileOutputStream() constructor. For example, FileOutputStream fos = new FileOutputStream(“File.txt", true);

27 More on Writing to a File The java.io.FileWriter class writes text files using the platform's default character encoding and the buffer size. If you need to change these values, construct an OutputStreamReader on a FileOutputStream instead. The java.io.FileWriter class writes text files using the platform's default character encoding and the buffer size. If you need to change these values, construct an OutputStreamReader on a FileOutputStream instead.

28 LineNumberReader class The java.io.LineNumberReader class is a subclass of java.io.BufferedReader that keeps track of which line you're currently reading. It has all the methods of BufferedReader including readLine(). It also has two constructors, getLineNumber(), and setLineNumber() methods: The java.io.LineNumberReader class is a subclass of java.io.BufferedReader that keeps track of which line you're currently reading. It has all the methods of BufferedReader including readLine(). It also has two constructors, getLineNumber(), and setLineNumber() methods: public LineNumberReader(Reader in)public LineNumberReader(Reader in) public LineNumberReader(Reader in, int size)public LineNumberReader(Reader in, int size) public int getLineNumber()public int getLineNumber() public void setLineNumber(int lineNumber) The setLineNumber() method does not change the file pointer. It just changes the value getLineNumber() returns.public void setLineNumber(int lineNumber) The setLineNumber() method does not change the file pointer. It just changes the value getLineNumber() returns. For example, it would allow you to start counting from -5 if you knew there were six lines of header data you didn't want to count. For example, it would allow you to start counting from -5 if you knew there were six lines of header data you didn't want to count.

29 Lets look at some examples First ---- using DataInputStream and DataOutputStream First ---- using DataInputStream and DataOutputStream

30 Data Input/Output Stream example import java.io.*; class DOSDISDemo { public static void main (String [] args) public static void main (String [] args) { DataOutputStream dos = null; DataOutputStream dos = null; try try { FileOutputStream fos = new FileOutputStream ("data.dat"); FileOutputStream fos = new FileOutputStream ("data.dat"); dos = new DataOutputStream (fos); dos = new DataOutputStream (fos); dos.writeInt (256); dos.writeInt (256); dos.writeDouble (Math.PI); dos.writeDouble (Math.PI); dos.writeUTF ("Java"); dos.writeUTF ("Java"); } catch (IOException e) catch (IOException e) { System.out.println (e.getMessage ()); { System.out.println (e.getMessage ()); return; } return; } finally finally { if (dos != null) { if (dos != null) try try { dos.close (); } { dos.close (); } catch (IOException e) { } catch (IOException e) { } } DataInputStream dis = null; DataInputStream dis = null; try try { FileInputStream fis = new FileInputStream ("data.dat"); FileInputStream fis = new FileInputStream ("data.dat"); dis = new DataInputStream (fis); dis = new DataInputStream (fis); System.out.println (dis.readInt ()); System.out.println (dis.readInt ()); System.out.println (dis.readDouble ()); System.out.println (dis.readDouble ()); System.out.println (dis.readUTF ()); System.out.println (dis.readUTF ()); } catch (IOException e) catch (IOException e) { System.out.println (e.getMessage ()); System.out.println (e.getMessage ()); return; return; } finally finally { if (dis != null) if (dis != null) try try { dis.close (); } { dis.close (); } catch (IOException e) { } catch (IOException e) { } } }} OUTPUT 256 3.141592653589793 Java

31 Another Example--- Piped Streams A Motivation? Threads are often required to communicate. Can use piped streams. IDEA= connect a piped output stream to a piped input stream. Then, one thread writes data to the piped output stream and another thread reads that data by way of the piped input stream. CAUTION= streams have limited sizes. As a result, a writing thread could write more output to a piped output stream than that stream can accommodate, and the excess output would be lost. To prevent that from happening, the reading thread must be responsive.

32 Buffered Streams, Piped Streams (here with same thread) import java.io.*; public class BufferedReaderTest { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { BufferedReader charStream = BufferedReader charStream = new BufferedReader (new InputStreamReader(System.in)); new BufferedReader (new InputStreamReader(System.in)); String data = charStream.readLine(); // Read a line from standard input String data = charStream.readLine(); // Read a line from standard input System.out.println("Input = " + data); System.out.println("Input = " + data); }} The Buffered stream classes buffer their data to avoid every read or write going directly to the next stream. These classes are often used in conjunction with File streams. The Buffered stream classes buffer their data to avoid every read or write going directly to the next stream. These classes are often used in conjunction with File streams. import java.io.*; class TextGenerator extends Thread { private Writer out; private Writer out; public TextGenerator(Writer out) { public TextGenerator(Writer out) { this.out = out; this.out = out; } public void run() { try { try { for (char c = 'a'; c <= 'z'; c++) for (char c = 'a'; c <= 'z'; c++) out.write(c); out.write(c); } finally { } finally { out.close(); out.close(); } } catch(IOException e) { } catch(IOException e) { getUncaughtExceptionHandler().uncaughtExcepti on(this, e); getUncaughtExceptionHandler().uncaughtExcepti on(this, e); } }} public class Pipe { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { PipedWriter out = new PipedWriter(); PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(out); PipedReader in = new PipedReader(out); TextGenerator data = new TextGenerator(out); TextGenerator data = new TextGenerator(out); data.start(); data.start(); int ch; int ch; while ((ch=in.read()) != -1) while ((ch=in.read()) != -1) System.out.print((char) ch); System.out.print((char) ch); System.out.println(); System.out.println(); }} Result: abcdefghijklmnopqrstuvwxyz InputStream Character Stream

33 Another Example--- LineNumberReader Tracks Line numbers as you are reading Tracks Line numbers as you are reading

34 Print Streams, LineNumberReader The Print streams provide methods that make it easy to write the values of primitive types and object to a stream, in a human-readable text format The Print streams provide methods that make it easy to write the values of primitive types and object to a stream, in a human-readable text format print and println methodprint and println method The call out.print(f) is equivalent to out.write(String.valueOf(f).getByt es()); The call out.print(f) is equivalent to out.write(String.valueOf(f).getByt es()); LineNumberReader LineNumberReader The LineNumberReader stream keeps track of line numbers while reading text. The LineNumberReader stream keeps track of line numbers while reading text. import java.io.*; public class FindChar { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { if (args.length != 2) if (args.length != 2) throw new IllegalArgumentException( throw new IllegalArgumentException( "need char and file"); "need char and file"); int match = args[0].charAt(0); int match = args[0].charAt(0); FileReader fileIn = new FileReader(args[1]); FileReader fileIn = new FileReader(args[1]); LineNumberReader in = new LineNumberReader(fileIn); LineNumberReader in = new LineNumberReader(fileIn); int ch; int ch; while ((ch = in.read()) != -1) { while ((ch = in.read()) != -1) { if (ch == match) { if (ch == match) { System.out.println("'" + (char) ch + System.out.println("'" + (char) ch + "' at line " + in.getLineNumber()); "' at line " + in.getLineNumber()); return ; return ; } } System.out.println((char) match + " not found"); System.out.println((char) match + " not found"); }} Run: %java FindChar I FindChar.java Result: ‘I’ at line 4

35 Another Example …Pushback Streams Pushback is used on an input stream to allow a byte to be read and then returned(that is "pushed back") to the stream. Pushback is used on an input stream to allow a byte to be read and then returned(that is "pushed back") to the stream. PushbackInputStream provides a mechanism to "peek " at what is coming from an input stream without disrupting it. PushbackInputStream provides a mechanism to "peek " at what is coming from an input stream without disrupting it. PushbackInputStream

36 Pushback Streams A Pushback stream lets you push back, or “unread” characters or bytes when you have read too far. Pushback is typically useful for breaking input into tokens. A Pushback stream lets you push back, or “unread” characters or bytes when you have read too far. Pushback is typically useful for breaking input into tokens. For example, lexical scanners often know that a token (such as an identifier) has ended only when they have read the first character that follows it. For example, lexical scanners often know that a token (such as an identifier) has ended only when they have read the first character that follows it. The following example uses PushbackInputStream to report the longest consecutive sequence of any single byte in its input: The following example uses PushbackInputStream to report the longest consecutive sequence of any single byte in its input: import java.io.*; public class SequenceCount { public static void main(String[] args) public static void main(String[] args) throws IOException throws IOException { PushbackInputStream PushbackInputStream in = new PushbackInputStream(System.in); in = new PushbackInputStream(System.in); int max = 0; // longest sequence found int max = 0; // longest sequence found int maxB = -1; // the byte in that sequence int maxB = -1; // the byte in that sequence int b; // current byte in input int b; // current byte in input do { do { int cnt; int cnt; int b1 = in.read(); int b1 = in.read(); for (cnt = 1; (b = in.read()) == b1; cnt++) for (cnt = 1; (b = in.read()) == b1; cnt++) continue; continue; if (cnt > max) { if (cnt > max) { max = cnt; // remember length max = cnt; // remember length maxB = b1; // remember which byte value maxB = b1; // remember which byte value } in.unread(b); // pushback start of ntext seq in.unread(b); // pushback start of ntext seq } while (b != -1); // until we hit end of input } while (b != -1); // until we hit end of input System.out.println(max + " byte of " + maxB); System.out.println(max + " byte of " + maxB); }} Run and Result: % java SequenceCount 12345111 ^D in Unix(or ^Z in Windows) 3 bytes of 49

37 Another Example Java I/O even has ability to read zip files Java I/O even has ability to read zip files java.util.zip java.util.zip ZipInputStream,ZipOutputStreamZipInputStream,ZipOutputStream

38 Zip File Example –will list contents // ZipReader.java import java.io.*; import java.util.zip.*; class ZipReader { public static void main (String [] args) public static void main (String [] args) { if (args.length != 1) if (args.length != 1) { System.out.println ("usage: java ZipReader pathname"); System.out.println ("usage: java ZipReader pathname"); return; return; } ZipInputStream zis = null; ZipInputStream zis = null; try try { FileInputStream fis = new FileInputStream (args [0]); FileInputStream fis = new FileInputStream (args [0]); zis = new ZipInputStream (fis); zis = new ZipInputStream (fis); ZipEntry ze; ZipEntry ze; while ((ze = zis.getNextEntry ()) != null) while ((ze = zis.getNextEntry ()) != null) System.out.println (ze.getName ()); System.out.println (ze.getName ()); } // ZipReader.java catch (IOException e) { System.out.println (e.getMessage ()); System.out.println (e.getMessage ()); } finally finally { try try { zis.close (); zis.close (); } catch (IOException e) catch (IOException e) { } } }} To run ZipReader, you need access to either a Zip file or a Jar file (which is basically a Zip file with a.jar extension To run ZipReader, you need access to either a Zip file or a Jar file (which is basically a Zip file with a.jar extension

39 A useful class in I/O –the StreamTokenizer The StreamTokenizer gives simple tokenization. The StreamTokenizer gives simple tokenization. More general facility for scanning and converting input text is provided by the java.util.Scanner class. More general facility for scanning and converting input text is provided by the java.util.Scanner class.

40 StreamTokenzier Four token type Four token type TT_WORDTT_WORD TT_NUMBERTT_NUMBER TT_EOLTT_EOL TT_EOFTT_EOF import java.io.*; class StreamTokenizerDemo { public static void main(String args[]) { public static void main(String args[]) { try { try { FileReader fr = new FileReader(args[0]); FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr); StreamTokenizer st = new StreamTokenizer(br); StreamTokenizer st = new StreamTokenizer(br); st.ordinaryChar('.'); st.ordinaryChar('.'); st.wordChars('\'', '\''); st.wordChars('\'', '\''); while(st.nextToken() != StreamTokenizer.TT_EOF) { while(st.nextToken() != StreamTokenizer.TT_EOF) { switch(st.ttype) { switch(st.ttype) { case StreamTokenizer.TT_WORD: case StreamTokenizer.TT_WORD: System.out.println(st.lineno() + ") " + System.out.println(st.lineno() + ") " + st.sval); st.sval); break; break; case StreamTokenizer.TT_NUMBER: case StreamTokenizer.TT_NUMBER: System.out.println(st.lineno() + ") " + System.out.println(st.lineno() + ") " + st.nval); st.nval); break; break; default: default: System.out.println(st.lineno() + ") " + System.out.println(st.lineno() + ") " + (char)st.ttype); (char)st.ttype); } } } } fr.close(); fr.close(); } catch (Exception e) { catch (Exception e) { System.out.println("Exception: " + e); System.out.println("Exception: " + e); } }} Input (tokens.txt ) The price is $23.45. Is that too expensive? (I don’t think so.) Run: java StreamTokenizerDemo tokens.txt Result 1) The 1) price 1) is 1) $ 1) 23.45 1). 2) Is 2) that 2) too 2) expensive 2) ? 3) ( 3) I 3) don’t 3) think 3) so 3). 3) )

41 Another on ….Data Byte Streams DataInput and DataOutput DataInput and DataOutput These interfaces define methods that transmit primitive types across a stream. These interfaces define methods that transmit primitive types across a stream. Read / Write methods Read / Write methods Read Write Type readBoolean writeBoolean boolean readChar writeChar char readByte writeByte byte readShort writeShort short readInt writeInt int readLong writeLong long readFloat writeFloat float readDouble writeDouble double readUTF writeUTF String(in UTF format) public static void writeData(double[] data, String file) throws IOException throws IOException{ OutputStream fout = new FileOutputStream(file); OutputStream fout = new FileOutputStream(file); DataOutputStream out = new DataOutputStream(fout); DataOutputStream out = new DataOutputStream(fout); out.writeInt(data.length) out.writeInt(data.length) for(double d : data) out.writeDouble(d); for(double d : data) out.writeDouble(d); out.close(); out.close();} public static double[] readData(String file) throws IOException throws IOException{ InputStream fin = new FileInputStream(file); InputStream fin = new FileInputStream(file); DataInputStream in = new DataInputStream(fin); DataInputStream in = new DataInputStream(fin); double[] data = new double[in.readInt()]; double[] data = new double[in.readInt()]; for (int i = 0; i < data.length; i++) for (int i = 0; i < data.length; i++) data[i] = in.readDouble(); data[i] = in.readDouble(); in.close(); in.close(); return data; return data;}

42 Reading and Writing Objects? What if we could save and store and object and read it (bring it back to life)….wow! What if we could save and store and object and read it (bring it back to life)….wow!

43 Object Serialization What is Object Serialization? What is Object Serialization? Serialization: process of converting an object’s representation into a stream of bytesSerialization: process of converting an object’s representation into a stream of bytes Deserialization: reconstituting an object from a byte streamDeserialization: reconstituting an object from a byte stream Process of reading and writing objectsProcess of reading and writing objects Writing an object is to represent its state in a serialized form sufficient to reconstruct the object as it is read.Writing an object is to represent its state in a serialized form sufficient to reconstruct the object as it is read. serialization is the process of converting a object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment.serialization is the process of converting a object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment.filenetworkfilenetwork

44 Serializing Objects How to Write to an ObjectOutputStream How to Write to an ObjectOutputStream Writing objects to a stream is a straight-forward process. Example of constructing a Date object and then serializing that object:Writing objects to a stream is a straight-forward process. Example of constructing a Date object and then serializing that object: FileOutputStream out = new FileOutputStream("theTime"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeObject("Today"); s.writeObject(new Date()); s.flush(); How to Read from an ObjectOutputStream How to Read from an ObjectOutputStream Example that reads in the String and the Date object that was written to the file named theTime in the read example: FileInputStream in = new FileInputStream("theTime"); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Date)s.readObject();

45 Serializing Objects Providing Object Serialization for Your Classes Providing Object Serialization for Your Classes Implementing the Serializable InterfaceImplementing the Serializable Interface Customizing SerializationCustomizing Serialization Implementing the Externalizable InterfaceImplementing the Externalizable Interface Protecting Sensitive InformationProtecting Sensitive Information

46 Files ---and Channels+

47 Accessing Files Channels Channels Channels were introduced in the 1.4 release of Java to provide a faster capability for a faster capability for input and output operations with files, network sockets, and piped I/O operations between programs than the methods provided by the stream classes.Channels were introduced in the 1.4 release of Java to provide a faster capability for a faster capability for input and output operations with files, network sockets, and piped I/O operations between programs than the methods provided by the stream classes. The channel mechanism can take advantage of buffering and other capabilities of the underlying operating system and therefore is considerably more efficient than using the operations provided directly within the file stream classes.The channel mechanism can take advantage of buffering and other capabilities of the underlying operating system and therefore is considerably more efficient than using the operations provided directly within the file stream classes. A summary of the essential role of each of them in file operations A summary of the essential role of each of them in file operations A File object encapsulates a path to a file or a directory, and such an object encapsulating a file path can be used to construct a file stream object.A File object encapsulates a path to a file or a directory, and such an object encapsulating a file path can be used to construct a file stream object. A FileInputStream object encapsulates a file that can be read by a channel. A FileoutputStream object encapsulates a file that can be written by a channel. A FileInputStream object encapsulates a file that can be read by a channel. A FileoutputStream object encapsulates a file that can be written by a channel. A buffer just holds data in memory. The loaded data to be written to a file will be saved at buffer using the buffer’s put() method, and retrieved using buffer’s get() methods. A buffer just holds data in memory. The loaded data to be written to a file will be saved at buffer using the buffer’s put() method, and retrieved using buffer’s get() methods. A FileChannel object can be obtained from a file stream object or a RandomAccessFile object. A FileChannel object can be obtained from a file stream object or a RandomAccessFile object.

48 Accessing Files The hierarchy of the channel interfaces

49 Accessing Files The Capacities of Different Buffers

50 Channel Example (ReadPrimes) import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ReadPrimes { public static void main(String[] args) { public static void main(String[] args) { File aFile = new File("primes.bin"); File aFile = new File("primes.bin"); FileInputStream inFile = null; FileInputStream inFile = null; try { try { inFile = new FileInputStream(aFile); inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { } catch(FileNotFoundException e) { e.printStackTrace(System.err); e.printStackTrace(System.err); System.exit(1); System.exit(1); } FileChannel inChannel = inFile.getChannel(); FileChannel inChannel = inFile.getChannel(); final int PRIMECOUNT = 6; final int PRIMECOUNT = 6; ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT); ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT); long[] primes = new long[PRIMECOUNT]; long[] primes = new long[PRIMECOUNT]; try { while(inChannel.read(buf) != -1) { while(inChannel.read(buf) != -1) { ((ByteBuffer)(buf.flip())).asLongBuffer().g et(primes); ((ByteBuffer)(buf.flip())).asLongBuffer().g et(primes); // List the primes read on the same line // List the primes read on the same line System.out.println(); System.out.println(); for(long prime : primes) for(long prime : primes) System.out.printf("%10d", prime); System.out.printf("%10d", prime); buf.clear(); // Clear the buffer for the next read buf.clear(); // Clear the buffer for the next read } System.out.println("\nEOF reached."); System.out.println("\nEOF reached."); inFile.close(); // Close the file and the channel inFile.close(); // Close the file and the channel } catch(IOException e) { } catch(IOException e) { e.printStackTrace(System.err); e.printStackTrace(System.err); System.exit(1); System.exit(1); } System.exit(0); System.exit(0); }} You also need to read the “PrimesToFile.java” which prints prime numbers to the file. Channel Setup Buffer Setup From the channel, read data and save to the buffer


Download ppt "Java I/O L. Grewe. Overview of java.io methods for accessing file, text data, object serialization and internationalization methods for accessing file,"

Similar presentations


Ads by Google