You are on page 1of 3

I/O package

The java.io package contains many classes that your programs can use to read and write data An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. A program uses an input stream to read data from a source, one item at a time. A program uses an output stream to write data to a destination, one item at time.

Types of Streams:
There are two types of stream depending on the data it deals with: 1. byte stream - Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream 2. character stream - Programs use character streams to perform input and output of 16bit character data. All character stream classes are descended from Reader and Writer. 1. To read from a file using byte stream import java.io.*; public class FileInputTest{ public static void main(String args[]){ try{ File f1 = new File("infile.txt"); FileInputStream fr = new FileInputStream(f1); int r; while((r = fr.read())!=-1){ System.out.println(s); } fr.close(); }catch(IOException e){e.printStackTrace();} } }

2. To read from and write to a file using byte stream import java.io.*; public class FileOutputTest{ public static void main(String args[]){ try{ File f1 = new File("infile.txt"); File f2 = new File("outFile.txt"); FileInputStream fr = new FileInputStream(f1); FileOutputStream fw = new FileOutputStream(f2); int r; while((r = fr.read())!=-1){ System.out.println(writing to the file..>>>>>); fw.write(r); } fr.close(); fw.close(); }catch(IOException e){e.printStackTrace();} } } 3. Using buffered streams to read a line from the file import java.io.*; public class BufferedReaderTest{ public static void main(String args[]){ try{ File f1 = new File("infile.txt"); File f2 = new File("outFile.txt"); FileReader fr = new FileReader(f1); FileWriter fw = new FileWriter(f2); BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(fw); String s; while((s = br.readLine())!=null){ System.out.println(s); } bw.close(); br.close(); }catch(IOException e){

e.printStackTrace(); } } } 4. Reading from the keyboard import java.io.*; public class KeyWriterTest{ public static void main(String args[]){ try{ File f2 = new File("outFile.txt"); FileWriter fw = new FileWriter(f2); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; System.out.print("Enter File Name :"); PrintWriter pw = new PrintWriter(new FileWriter(br.readLine())); while((s = br.readLine())!=null){ if(s.equals("exit")){ break; } pw.println(s); } pw.close(); br.close(); }catch(IOException e){e.printStackTrace();} } }

You might also like