Io

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Io as PDF for free.

More details

  • Words: 3,271
  • Pages: 13
JAVA I/O SYSTEM

0 111 101 010 100 001 110 0 011 110 001 111 000 011 110 011

Hard Disk

Main Memory Java Program

IO Stream

Text File

Stream A Stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java System. All Streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kind of input: from a disk file, a keyboard, or a network connection. Streams are a clean way to deal with input/output without having every part of your code understands the difference between a keyboard and a network. Byte Stream & Character Stream : Java define two types of streams :byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input & output of characters. They used Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte stream.

IO Stream

Character Stream

Byte Stream

InputStream

OutputStream

AudioInputStream,

ByteArrayOutputStream

ByteArrayInputStream

FileOutputStream

FileInputStream

FilterOutputStream

FilterInputStream

BufferedOutputStream

BufferedInputStream ObjectInputStream StringBufferInputStrea DataInputStream

ObjectOutputStream PipedOutputStream DataOutputStream

Reader

Writer

BufferedReader

BufferedWriter

LineNumberReader

CharArrayWriter

FilterReder

FilterWriter

InputStreamReader

InputStreamWriter

FileReader

FileWriter

StringReader

PrintWriter

CharArrayReader

StringWriter

PrintStream

Byte Reading & Writing Byte Streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream, OutputStream. Each of these abstract classes has several concrete classes that handle the differences between various devices, such as disk files, network connections. The abstract classes InputStream & OutputStream define several key methods that the other stream classes implement. Two of the most important are read() & write(), which, respectively, read and write bytes of data. 1

Example 1.Byte Reading (Read values form the Keyboard)

class SystemInRead{ public static void main(String args[])throws java.io.IOException{ int x; char ch; System.out.print("Press a key.."); x=System.in.read(); System.out.println("Read ASSCI value of the Input Key :"+x );; System.out.println("The key of you pressed :"+(char)x); } }

Example 2.A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. import java.io.*; class DemoByteArrayInputStream{ public static void main(String args[]){ byte b[]={65, 67,69,71,73,75,77,79}; ByteArrayInputStream bis=new ByteArrayInputStream(b); int x; while((x=bis.read())!=-1){ System.out.println(x+" :"+(char)x); } } }

Example 3./* 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; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File Not Found"); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: File not found "); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } } 2

fin.close();

Example 4. A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. import java.io.*; class DemoFileInputStream { public static void main(String args[])throws IOException{ byte b[]={65, 67,69,71,73,75,77,79}; FileInputStream fis=new FileInputStream("Input.txt"); int x; while((x=fis.read())!=-1){ System.out.print((char)x); if(x==0) System.out.println(); } System.out.println(); } }

Example 5.A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. import java.io.*; class TestDataInputStream { public static void main(String args[])throws IOException{ FileInputStream fis=new FileInputStream("Input.txt"); DataInputStream dis=new DataInputStream(fis); byte b; while((b=dis.readByte())!=-1){ System.out.print((char)b); if(b==0) System.out.println(); } System.out.println(); }

}

FileOutpuStream A FileOutputStream is an output stream for writing data to a File. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time.

Example 6.FileOutputStream import java.io.*; class DemofileOutputStreamStream { public static void main(String args[])throws IOException{ FileOutputStream fos=new FileOutputStream("Output.txt",true); //Creates an output file stream to write to the file with the specified name. byte

b[]={78,105,114,111,116,104,32,76,97,107,109,97,108,32,83,97, 109,97,114,97,119,105,99,107,114,97,109,97,13,10,78,111, 46,53,48,54,32,49,47,51,44,13,10,71,97,108,108, 101,32,82,100,44,13,10,80,97,110,97,100,117,114,97,46}; fos.write(b); //Print data of text file "Output.txt" FileInputStream fis=new FileInputStream("Output.txt"); int x; while((x=fis.read())!=-1){ System.out.print((char)x); if(x==0) System.out.print((char)x); } System.out.println(); 3

}}

Example 7.

/* 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 */ 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; } // 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; } // 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();

} PrintStream A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. PrintStream(File file) Creates a new print stream, without automatic line flushing, with the specified file. PrintStream(OutputStream out) Create a new print stream. 4

PrintStream(String fileName)

Example 8.PrintStream (Print to a Text file) import java.io.*; class DemoPrintStream { public static void main(String args[])throws IOException{ PrintStream ps=new PrintStream("PrintText.txt"); //Creates a new print stream, without automatic line flushing, //with the specified file name. ps.print("Institute of Java & Technological Studies\n"); ps.print(123.34); ps.print(123.34f); ps.print(123); } } Example 9.PrintStream (Print to the console) import java.io.*; class DemoPrintStream2 { public static void main(String args[])throws IOException{ PrintStream ps=new PrintStream(System.out); //Creates a new print stream, without automatic line flushing, //with the specified file name. ps.print("Institute of Java & Technological Studies\n"); ps.print(123.34); ps.println(123.34f); ps.print(123); } }

Character Reading & Writing Character streams are defined by using class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete sub classes of each of these. The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read() & write(), which read and write characters of data, respectively. Using InputStreamReader Reading Character

IO Stream InputStreamReader(System.in)

C ha ra ct er s

1 0 0 0 01 0 11 1 10 1 10 10 1 01 0 0 10 10 1 1 01 0 0 10 1 1 1 Keyboard

Java Program

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

Example 10. InputStreamReader(Keyboard) Reader Characters from a Text file FileInputStream(“Input.txt”) C ha ra ct er s

1 0 0 0 0 56 1 66 1 65 76 1 67 0 0 0 1 1 1 01 1 01 0 01 0 11 0 10 10 1 10 1 1 1 0 0 0 0 1 1 1 1 0

Hard Disk

InputStreamReader(FileInputStream) Input.txt

=x Java Program

Example 11.(InputStreamReader)

import java.io.*; class DemoInputStreamReader2{ public static void main(String args[])throws IOException{ 5

}

InputStreamReader isr=new InputStreamReader(System.in); //Create an InputStreamReader that uses the input from the keyboard System.out.print("Input Character :"); int x=isr.read(); //This method read a character from the keyboard System.out.println(x+" "+(char)x);

}

Example 12. InputStreamReader with FileInputStream Read character from file (Input.txt) import java.io.*; class DemoInputStreamReader3{ public static void main(String args[])throws IOException{ InputStreamReader isr1=new InputStreamReader(new FileInputStream("Input.txt")); while((x=isr1.read())!=-1){ System.out.print((char)x); } isr.close(); } }

Example 13.BufferedReader

import java.io.*; class DemoBufferedReader { public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("Input.txt"))); String s; while((s=br.readLine())!=null){ System.out.println(s); } }} Example 14.BufferedReader import java.io.*; class DemoBufferedReader2 { public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int x,y,z; System.out.print("Input a Number :"); x=Integer.parseInt(br.readLine()); System.out.print("Input a Number :"); y=Integer.parseInt(br.readLine()); z=x+y; System.out.println("X + Y :"+z); }

}

FileReader IO Stream

65 56 76 65 56

01 11 10 10 10

1 0 0 0 0 1 1 1 0 0 0 1 1

Hard Disk

Java Program

FileReader(“Input.txt”) Input.txt

Example 15. import java.io.*; class DemoFileReader { public static void main(String args[])throws IOException{ FileReader fr=new FileReader("Input.txt"); int x; while((x=fr.read())!=-1){ System.out.println((char)x); 6

}

}

}

IO Stream

FileReader(“Input.txt”)

Ni rot h Sa m ar a wi ck ra m a

65 56 56 68 90

01 11 10 10 10

1 0 0 0 0 1 1 1 0 0 0

Hard Disk

Java Program

DufferedReader(FileReader)

Input.txt

Example 16. import java.io.*; class DemoFileReader2 { public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new FileReader("Input.txt")); String s; while((s=br.readLine())!=null){ System.out.println(s); } } }

Writing Characters Example 17.BufferedWriter BufferedWriter class can write strings to a Disk file using FileWriter stream import java.io.*; class DemoBufferedWriter1 { public static void main(String args[])throws IOException{ BufferedWriter bw=new BufferedWriter(new FileWriter("Output.txt")); String s="Institute of Java & Technological Studies"; bw.write(s); bw.close(); } }

Example 18.InputStreamWriter(Console) This program demonstrates how write characters on console using OutputStreamWriter import java.io.*; class DemoOutputStreamWriter{ public static void main(String args[])throws IOException{ OutputStreamWriter bw=new OutputStreamWriter(System.out); String s="Institute of Java & Technological Studies"; bw.println(s); bw.close(); } }

Example 19.InputStreamWriter(FileOutputWriter) import java.io.*; class DemoOutputStreamWriter2{ public static void main(String args[])throws IOException{ FileOutputStream fos= new FileOutputStream("Input.txt"); 7

OutputStreamWriter osw=new OutputStreamWriter(fos); String s1="Institute of Java & Technological Studies"; String s2="No 506 1/3, Galle Road,"; String s3="Panadura."; osw.write(s1); osw.write(s2); osw.write(s3); osw.close(); }

}

PrintWriter PrintWriter(File file)

Creates a new PrintWriter, without automatic line flushing, with the specified file. PrintWriter(OutputStream out)

Create a new PrintWriter, without automatic line flushing, from an existing OutputStream. PrintWriter(OutputStream out, boolean autoFlush)

Create a new PrintWriter from an existing OutputStream. PrintWriter(String fileName)

Creates a new PrintWriter, without automatic line flushing, with the specified file name. PrintWriter(Writer out)

Create a new PrintWriter, without automatic line flushing. PrintWriter(Writer out, boolean autoFlush)

Create a new PrintWriter. Example 20.PrintWriter(System.out) import java.io.*; class DemoPrintWriter{ public static void main(String args[])throws IOException{ PrintWriter pw=new PrintWriter(System.out, true ); pw.println("Institute of Java & Technlogical Studies"); pw.println("No. 506 1/3, Galle Rd,"); pw.println("Panadura."); pw.println(); pw.write(65); pw.write(32); pw.println(); pw.append('g'); pw.println(); pw.println(23.34); pw.println(23); pw.flush(); } }

Example 21.PrintWriter(“DiskFile”) import java.io.*; class DemoPrintWriter2{ public static void main(String args[])throws IOException{ PrintWriter pw=new PrintWriter("Output.txt" ); pw.println("Institute of Java & Technlogical Studies"); pw.println("No. 506 1/3, Galle Rd,"); pw.println("Panadura."); pw.println(); pw.write(65); pw.write(32); pw.println(); pw.append('g'); 8

pw.println(); pw.println(23.34); pw.println(23); pw.flush(); }

}

StringWriter() A character stream that collects its output in a string buffer, which can then be used to construct a string. StringWriter() Create a new string writer, using the default initial string-buffer size. StringWriter(int initialSize) Create a new string writer, using the specified initial string-buffer size.

Example 22.StringWriter() import java.io.*; class DemoStringWriter{ public static void main(String args[])throws IOException{ StringWriter sw=new StringWriter(); sw.write("IJTS"); System.out.println(sw); sw.write("- Institute of Java & Technological Studies"); System.out.println(sw); } }

ObjectInputStream & ObjectOutputStream ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.

Example 23.ObjectOutputStream Constructors ObjectOutputStream(OutputStream out) Creates an ObjectOutputStream that writes to the specified OutputStream. import java.io.*; class Cat implements Serializable { int age; String name; Cat(String n, int a){ name=n; age=a; } void printCat(){ System.out.println("Name of the cat:"+name); System.out.println("Age of the cat:"+age); } } 9

// Serialize a cat object and save it on a disk file(CatObject.ser) class DemoObjectOutputStream{ public static void main(String args[]) throws Exception{ FileOutputStream fis=new FileOutputStream("CatObjects.ser"); ObjectOutputStream oos=new ObjectOutputStream(oos);

}

Cat c1=new Cat("Kit", 4); oos.writeObject(c1);

} // Serialize a cat object and save it on the console (but cannot read it) class DemoObjectOutputStream{ public static void main(String args[]) throws Exception{ ObjectOutputStream oos=new ObjectOutputStream(System.out);

}

Cat c1=new Cat("Kit", 4); oos.writeObject(c1);

}

File Navigation and I/O File The API says that the class Fi le is "An abstract representation of file and directory pathnames." The File class isn't used to actually read or write data; it's used to work at a higher level, making new empty files, searching for files, deleting files, making directories, and working with paths. Following constructors can be used to create File objects: File(String directorypath); File(String derectorypath, String filename); File(File dirObj, String filename); File(URI uriObj); E.g. File f1=new File(“/”); File f2=new File(“/”,”autoexec.bat”); File f3=new File(f1,”autoexec.bat”); The first Fi le object is constructed with a directory path as the only argument. The second includes two arguments-the path and the file name. The third includes the file path assign to f1 and a file name; f3 refers to the same file as f3. File defines many methods that obtain the standard properties of a file object. For example, get Na me () returns the name of the file, get Pa re nt () returns the name of the parent directory, and exist s( ) returns true if the file is exists, false if it does not.

Example 24. import java.io.*; class FileDemo1 { static void p(String s) { System.out.println(s); } public static void main(String args[])throws Exception { File f1 = new File("E:/java/File/MyTextFile.txt"); PrintWriter pw=new PrintWriter(f1); pw.append("No. 506 1/3"); pw.flush(); p("File Name: " + f1.getName()); 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"); 10

} }

Example 25. import java.io.*; class CreateAFile { public static void main(String [] args) { try { // warning: exceptions possible boolean newFile = false; File file = new File("fileWrite1.txt"); // it's only an object System.out.println(file.exists()); // look for a real file newFile = file.createNewFile(); // maybe create a file! System.out.println(newFile); // already there? System.out.println(file.exists()); // look again } catch(IOException e) { } } }

If you compile and run this program, when you look at the contents of your current directory, you'll discover absolutely no indication of a file called fileWrite1.txt. When you make a new instance of the class File, you're not yet making an actual file, you're just creating a filename.

Example 26.

import java.io.*; class DemoFileDirectory { static void p(String s) { System.out.println(s); } public static void main(String args[])throws Exception { File f1 = new File("E:/java/File");//Here is only directory path

}

String fileList[]=f1.list(); for(String fileName:fileList) p(fileName);

}

Example 27.Filtering File types import java.io.*; class MyFileFilter implements FilenameFilter{ String fileExtension="."; MyFileFilter(String n){ fileExtension+=n; } public boolean accept(File dir, String name){ return name.endsWith(fileExtension); //gives end style of the file name //If the fileExtension is math returns true otherwise false } } class DemoFileDirectory { static void p(String s) { System.out.println(s); } public static void main(String args[])throws Exception { File f1 = new File("E:/java/File"); System.out.println("Here are all MS Word files....."); String fileList[]=f1.list(new MyFileFilter("doc")); 11

for(String fileName:fileList) p(fileName); System.out.println("\n\n Here are all Text files....."); for(String fileName:f1.list(new MyFileFilter("txt"))) p(fileName); } }

Directories A directory is a File that contains list of other files and directories. When you create a File object and it is a directory, the isDirectory() method will return true. In this case, you can call lis() on that object to extract the list of other files and directories inside. It has two forms. String[] list(); // Using directories. import java.io.File;

Example 28.Test

File Directory 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); 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"); } }}

Exam Objectives I/O is a huge topic in general, and the Java APIs that deal with I/O in one fashion or another are correspondingly huge. A general discussion of I/O could include topics such as file I/O, console I/O, thread I/O, high-performance I/O, byte-oriented I/O, character-oriented I/O, I/O filtering and wrapping, serialization, and more. Luckily for us, the I/O topics included in the Java 5 exam are fairly well restricted to file I/O for characters, and serialization. Here's a summary of the I/O classes you'll need to understand for the exam: File The API says that the class File is "An abstract representation of file and directory pathnames." The File class isn't used to actually read or write data; it's used to work at a higher level, making new empty files, searching for files, deleting files, making directories, and working with paths. FileReader This class is used to read character files. Its read() methods are fairly lowlevel, allowing you to read single characters, the whole stream of characters, or a fixed number of characters. FileReaders are usually wrapped by higher-level objects such as BufferedReaders, which improve performance and provide more convenient ways to work with the data. BufferedReader This class is used to make lower-level Reader classes like FileReader more efficient and easier to use. Compared to FileReaders, BufferedReaders read relatively large chunks of data from a file at once, and keep this data in a buffer. When you ask for the next character or line of data, it is retrieved from the buffer, which minimizes the number of times that time-intensive, file read operations are performed. In addition, BufferedReader provides more convenient methods such as readLine(), that allow you to get the next line of characters from a file. FileWriter This class is used to write to character files. Its write() methods allow you to write character(s) or Strings to a file. FileWriters are usually wrapped by higher-level Writer objects such as BufferedWriters or PrintWriters, which provide better performance and higher-level, more flexible methods to write data. 12

BufferedWriter This class is used to make lower-level classes like FileWriters more efficient and easier to use. Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file writing operations are performed. In addition, the BufferedWriter class provides a newLine() method that makes it easy to create platform-specific line separators automatically. PrintWriter This class has been enhanced significantly in Java 5. Because of newly created methods and constructors (like building a PrintWriter with a File or a String), you might find that you can use PrintWriter in places where you previously needed a Writer to be wrapped with a FileWriter and/or a BufferedWriter. New methods like format(), printf(), and append() make PrintWriters very flexible and powerful.

13

Related Documents

Io
April 2020 29
Io
November 2019 42
Io
November 2019 42
Io
May 2020 27
Io Layer
June 2020 22
Io - 2
November 2019 27