Presentation is loading. Please wait.

Presentation is loading. Please wait.

I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.

Similar presentations


Presentation on theme: "I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader."— Presentation transcript:

1 I / O in java

2 java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter InputStream InputStreamReader LineNumberInputStream LineNumberReader ObjectInputStream ObjectInputStream.GetField ObjectOutputStream ObjectOutputStream.PutField ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringBufferInputStream StringReader StringWriter Writer

3 Topics to be covered I/O Streams –Byte Streams handle I/O of raw binary data.Byte Streams –Character Streams handle I/O of character data, automatically handling translation to and from the local character set.Character Streams –Buffered Streams optimize input and output by reducing the number of calls to the native API.Buffered Streams –Scanning and Formatting allows a program to read and write formatted text.Scanning and Formatting –I/O from the Command Line describes the Standard Streams and the Console object.I/O from the Command Line –*Data Streams handle binary I/O of primitive data type and String values.Data Streams –*Object Streams handle binary I/O of objects.Object Streams File I/O –File Objects help you to write platform-independent code that examines and manipulates files.File Objects –*Random Access Files handle non-sequential file access.Random Access Files * To be covered, by yourself

4 I/O Streams Java program perform all I/O operations through streams A stream is an abstraction that either consumes or produces information An input stream produces a stream of characters; an output stream receives a stream of characters, “one at a time.” All streams behave in a similar manner(independent of the device, they are linked to;viz diskfile, console or a network socket) Java implements streams within class hierarchies defined in java.io package.

5 Byte Streams Byte streams provide a convenient means for handling input and output of bytes. These are used, when reading or writing binary data. Byte streams are defined by using two class hierarchies.At the top are two abstract classes : InputStream, OutputStream The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two most important methods are read() and write(). The following programs uses byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. InputStream OutputStream There are many byte stream classes. Here the FileInputStream and FileOutputStreams are being used. Byte streams should only be used for the most primitive I/O

6 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( “ in.txt"); out = new FileOutputStream("out.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } //while }//try finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }

7 Character Streams Character Streams provide a convenient way for handling input and output of characters. They use Unicode and therefore can be internationalized. In most cases character streams are more efficient than byte streams. The lowest level IO is still byteoriented. In character Streams at the top there are two classes Reader and Writer. These two classes define several methods out of these read() and write() are the two important ones.

8 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(“in.txt"); outputStream = new FileWriter(“out.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }

9 Reading Console Input The preferred method of reading console input for Java is to use character oriented streams In Java, console input is accomplished by reading from System.in(predefined stream), which is wrapped in BufferedReader object. In case of unbuffered io the read and write requests are handled by underlying os. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full A program can convert a unbuffered stream into a buffered stream using the wrapping idiom we've used several times now –inputStream = new BufferedReader(new FileReader( “ in.txt")); –outputStream = new BufferedWriter(new FileWriter( “ out.txt"));

10 Import java.io.*; Class consoleRead { public static void main(String s[]) throws IOException{ char c; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(“Enter characters, q to quit”); do{ c=(char) br.read(); system.out.println©; }while(c!=‘q’); }

11 Reading/Writing Strings/Lines Character I/O usually occur in bigger units than single characters

12 import java.io.*; public class CopyLines { public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } Import java.io.*; Class ReadLines { Public static void main(String s[]) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(system.in)); String str; str=br.readLine(); System.out.println(str); }

13 File File class doesnot operate on streams It donot specify how information is being retrieved from or stored in files; but the properties of a file itself. Constructors –File(String directorypath) –File(String directorypath, String filename) –File(File dirObj, String filename)

14 Import java.io.*; Class filedemo{ Static void P(String s){System.out.println(s);} public static void main(String s[]) throws IOException { File f1= new File( “c:/jdk1.4/bin/COPYRIGHT”); P(“file name:”+f1.getName()); P(“Path:”+f1.getPath(); P(“Abs Path :”+f1.getAbsolutePath()); } Other methods getParent() exists() canWrite() canRead() isDirectory() isFile() lastModified() length() list()

15 Formatted Output Use DecimalFormat to control spacing and formatting (java has no printf statement) Approach 1.Create a DecimalFormat object describing the formatting DecimalFormat formatter=new DecimalFormat(“#,###.##”); 2.Then use the format method to convert values into formatted strings formatter.format(24.99);

16 Formatting Characters SymbolMeaning 0Placeholder for digit #Placeholder for digit without showing training zeros.Location of decimal point,Location of Comma -Minus Sign EScientific Notation %Multiply the value by 100 and display as %

17 NumberFormat Example Import java.text.*; Public class NumberFormat { public static void main(String s[]) { DecimalFormat science=new DecimalFormat(“0.000E0”); DecimalFormat plain=new DecimalFormat(“0.0000”); for (double d=100.0;d<140.0;d*=1.10) { System.out.println(“Scientific : “+ science.format(d) + “ and plain : “ + plain.format(d)); }}}

18 Alternate format specification public class Root2 { public static void main(String[] args) { int i = 2; double r = Math.sqrt(i); System.out.format("The square root of %d is %f.%n", i, r); } d formats an integer value as a decimal value. f formats a floating point value as a decimal value. n outputs a platform-specific line terminator. x formats an integer as a hexadecimal value. s formats any value as a string. tB formats an integer as a locale-specific month name. There are many other conversions.

19 Serialization Just as data streams support I/O of primitive data types, object streams support I/O of objects Most, but not all, standard classes support serialization of their objects. Those that do implement the marker interface Serializable.Serializable The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutputObjectInputStream ObjectOutputStream ObjectInputObjectOutput


Download ppt "I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader."

Similar presentations


Ads by Google