• No results found

IO Streams & Files

In document Java Notes (Page 189-200)

Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the internal memory and an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file.

A Stream is an abstraction for the source or destination of data. The source or destination can be anything , disk, memory buffer, network connection.

A Stream will have methods to operate on the data from the source or destination tied with them.

Types of Stream

An Input stream reads data where as an output stream write data. Byte streams read or write bytes where as charcter streams read or write

characters.

Stream methods are synchronized and they will wait for the data to be avialable then perform operation, and return. Lowlevel streams work with raw bytes, as stored by the file system and

usefull for taking an image of the data stored.

Highlevel streams work with charcter and primitive types , objects and provide meaningful entries for the programmer. It is possible to chain streams to provide new functionality.

Byte Streams

They can handle only 8-bit Bytes. They are abstracted by classes

InputStream and OutputStream . There are specialized classes derived from above abstract classes ,to handle reading and writing bytes.

The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below:

The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below:

OutputStream is also inherited from the Object class. Each class of the outputStreams provided by the java.io package is intended for a different purpose.

The FileInputStream handles byte oriented inputs from files. The

BufferedInputStream can use methods to move backwards in a buffered stream. In a BufferedOuptutStream we dont haver to write data to disk for each byte, but it can buffered and force a flush operation at once.

The DataInputStream can handle data in primitive types.

Example 140 : Demo of of FileInputStream

import java.io.*;

public class DemoTest {

public static void main(String args[]) throws Exception {

FileInputStream f = new FileInputStream ("DemoTest.java");

int len = f.avilable();

System.out.println("Available bytes: " + len);

System.out.println("Reading 1/5 of file....");

byte b[] = new byte[len/5];

f.read(b);

// convert byte array into string

System.out.println(new String(b, 0, b.length ));

System.out.println("Skipping ");

f.skip(len/5);

System.out.println("Reading next 1/5 of file....");

if (f.read(b) != len/5) {

System.out.println("Could not get ");

} else {

System.out.println(new String(b, 0, b.length) );

} f.close();

} }

Example 141 : Demo of of FileOutputStream import java.io.*;

public class Fdemo {

public static void main(String args[]) throws Exception {

byte data[] = "This is a string of text.".getBytes();

FileOutputStream f1 = new FileOutputStream("file1.txt");

for (int i = 0; i < data.length; i++) {

f1.write(data[i]);

}

FileOutputStream f2 = new FileOutputStream("file2.txt");

f2.write(data);

FileOutputStream f3 = new FileOutputStream("file3.txt");

f3.write(data, 5, 10);

f1.close();

f2.close();

f3.close();

} }

Example 142 : Demo of DataOutputStream & DataInputStream They permit reading or writing of primitive data types. After read we have to use methods to convert them to character, or string inorder to understand

import java.io.*;

public class DemoDataIO {

public static void main(String[] args) throws IOException {

DataOutputStream out = new DataOutputStream( new FileOutputStream("datas.txt" ));

double[] prices = { 9.99, 4.99, 15.99, 3.99 };

int[] units = { 12, 6, 10, 9 };

String[] descs = { "mangos", "oranges ", "apples", "corn"};

for (int i = 0; i < prices.length; i++) {

out.writeDouble(prices[i]);

out.writeChar('\t');

out.writeInt(units[i]);

out.writeChar('\t');

out.writeChars(descs[i]);

out.writeChar('\n');

}

out.close();

// now read the data from the file

DataInputStream in = new DataInputStream( new FileInputStream("datas.txt"));

double price;

int unit;

String desc;

double total = 0.0;

try {

while (true) {

price = in.readDouble();

in.readChar(); // throws out the tab unit = in.readInt();

in.readChar(); // throws out the tab desc = in.readLine();

System.out.println( price );

System.out.println( unit );

System.out.println( desc );

total = total + unit * price;

} }

catch (EOFException e) {

}

in.close();

} }

Character Streams

They support Reader, Writer Abstract classes for reading or writing 16 bit charcter inputs or outputs. These abstract classes have child classes to support operations.

Object | Reader |

______ | _________

| |

BufferedReader InputStreamReader |

FileReader

Object |

Writer |

_________________________________________

| | | BufferedWriter OutputStreamWriter PrintWriter |

FileWriter

The InputStreamReader can read data from keyboard thorugh System.in, and its counter part is OutputStreamWriter.

FileReader, FileWriter classes can handle streams from files. BufferedReader can read line by line instead of character by char.

PrinWriter can send formated outputs.

Example 143 : Demo of FileWriter import java.io.*;

class Demotest {

public static void main(String args[]) throws Exception {

char data[ ] ={ 'T', 'h', 'i', 's', ' ' ,

'i', 's', ' ' ,

'a', ' ' ,

'B' , ‘o', ‘o', ‘k’ };

FileWriter f = new FileWriter("file1.txt");

for (int i = 0; i < data.length; i++) {

f.write(data[i]);

}

FileWriter f2 = new FileWriter("file2.txt");

f2.write(data);

FileWriter f3 = new FileWriter("file3.txt");

f3.write(data, 5, 10);

f3.append(" made in java ");

f1.close();

f2.close();

f3.close();

} }

Example 144 : Demo of BufferedReader

We use this class to create character based stream that reads from a file line by line instead of character by character.

import java.io.*;

public class DemoTest {

public static void main(String args[]) throws Exception {

FileReader f = new FileReader("file3.txt");

BufferedReader bf = new BufferedReader(f);

while( true ) {

String x = bf.readLine( );

if ( x == null ) break;

else

System.out.println(x);

} bf.close( );

f.close( );

} }

Example 145 : Demo of InputStreamReader It is used to read the data typed from the keyboard.

import java.io.*;

class InputStreamReaderDemo {

public static void main(String args[]) {

try {

int c;

InputStreamReader ir = new InputStreamReader(System.in);

while ( (c = ir.read() ) != -1) {

System.out.print( (char) c);

} }

catch (IOException e) { }

} }

Object Serialization

It is a process of writing objects to a stream, and reading them back when wanted.

We use ObjectInputStream, ObjectOutputStream classes respectively which are derived from InputStrem, OutputStream classes to handle the Objects which are called object streams.

Example 146 : Demo of Object streams.

To serailize an object it should implement a Serializable interface.

import java.io.*;

class NewString implements Serializable

{

String d;

public NewString( String p) {

d = p;

}

public void dispdata( ) {

System.out.println(d);

} }

public class DemoTest {

public static void main(String args[]) {

NewString i1, o1;

i1 = new NewString("");

o1 = new NewString("Hello from Java!");

try {

FileOutputStream fo = new FileOutputStream ("testobj.dat");

ObjectOutputStream ofo = new ObjectOutputStream(fo);

ofo.writeObject(o1);

ofo.flush();

ofo.close();

FileInputStream fi= new FileInputStream ( testobj.dat");

ObjectInputStream ofi = new ObjectInputStream(fi) ; i1 = (NewString)ofi.readObject();

i1.dispdata();

ofi.close();

}

catch(Exception e) { } System.out.println(i1);

} }

Example 147 : Demo of Object streams.

To serailize an object it should implement a Serializable interface.

import java.io.*;

import java.util.*;

class Student implements Serializable {

int htno;

String name;

public Student(int x, String p) {

htno = x;

name = p;

}

public Student( ) { }

public int getHtno( ) {

return htno;

}

public String getName( ) {

return name;

} }

public class DemoObj {

public static void main(String args[]) {

Student i1, i2, o1,o2;

o1 = new Student(213, "Preethi");

o2 = new Student(123, "Pushkal");

try {

FileOutputStream fo = new FileOutputStream ("student.dat");

ObjectOutputStream ofo = new ObjectOutputStream(fo);

ofo.writeObject(o1);

ofo.writeObject(o2);

ofo.flush();

ofo.close();

FileInputStream fi= new FileInputStream("student.dat");

ObjectInputStream ofi = new ObjectInputStream(fi) ; i1 = (Student)ofi.readObject();

i2 = (Student)ofi.readObject();

ofi.close();

}

catch(Exception e) { }

System.out.println(i1);

System.out.println(i2);

} }

StreamTokenizer

It is used to break the input stream into tokens, such as words.

Example 148 : Demo of StreamTokenizer.

import java.io.*;

class DemoTest {

public static void main(String args[]) throws Exception {

FileReader f = new FileReader("file.txt");

StreamTokenizer st = new StreamTokenizer(f);

String s;

while(st.nextToken() != StreamTokenizer.TT_EOF) {

if(st.ttype == StreamTokenizer.TT_WORD)

System.out.println(st.sval);

}

f.close();

} }

File Streams

They are used to store the path and the name of the file or a Directory. It is not useful in retrieving or storing data. The File object can be used to create, rename, delete a file.

A directory is just a list of files. Each file in java is an object of File class.

File class can identify information such as last modification, date, time and navigation through subdirectories.

Example 149 : Demo of File Class.

import java.io.*;

class FileDemo {

public static void main(String args[]) {

File f1 = new File("file.txt");

System.out.println("File: " + f1.getName());

System.out.println( (f1.isFile() ? + is a file");

System.out.println("Size: " + f1.length());

System.out.println("Path: " + f1.getPath());

System.out.println("Parent: " + f1.getParent());

System.out.println("Absolute Path: " + f1.getAbsolutePath());

System.out.println("File was last modified: " + f1.lastModified());

System.out.println(f1.exists() ? "File exists" : "File does not exist");

System.out.println(f1.canRead() ? "File can be read from" : "File cannot

b e read from");

System.out.println(f1.canWrite() ? "File can be written to" : "File cannot be

written to");

In document Java Notes (Page 189-200)