Home | | Object Oriented Programming | Java I/O – The Basics

Chapter: Object Oriented Programming(OOP) : Java Exception Handling

Java I/O – The Basics

Java I/O is based around the concept of a stream

JAVA I/O – THE BASICS

         Java I/O is based around the concept of a stream

–   Ordered sequence of information (bytes) coming from a source, or going to a

‘sink’

–   Simplest stream reads/writes only a single byte, or an array of bytes at a time

 

 

         Designed to be platform-independent

         The stream concept is very generic

–   Can be applied to many different types of I/O

–   Files, Network, Memory, Processes, etc

         The java.io package contains all of the I/O classes.

–   Many classes specialised for particular kinds of stream operations, e.g. file I/O

         Reading/writing single bytes is quite limited

–   So, it includes classes which provide extra functionality

–   e.g. buffering, reading numbers and Strings (not bytes), etc.

 

         Results in large inheritance hierarchy, with separate trees for input and output stream classes

 

Java I/O – InputStream

 


Java I/O – InputStreams

         I/O in Java:

 

InputStream in = new FileInputStream(“c:\\temp\\myfile.txt”); int b = in.read();

 

//EOF is signalled by read() returning -1 while (b != -1)

 

{

 

//do something… b = in.read();

 

}

in.close();

 

• But using buffering is more efficient, therefore we always nest our streams… InputStream inner = new FileInputStream(“c:\\temp\\myfile.txt”);

 

InputStream in = new BufferedInputStream(inner); int b = in.read();

 

//EOF is signalled by read() returning -1

 

while (b != -1)

{

 

//do something… b = in.read();

 

}

in.close();

         We’ve omitted exception handling in the previous examples

 

         Almost all methods on the I/O classes (including constructors) can throw an IOException or a subclass.

 

         Always wrap I/O code in try…catch blocks to handle errors.

I/O – OutputStream

 


 

OutputStream out = null; try

 

{

 

OutputStream inner = new FileOutputStream(“c:\\temp\\myfile.txt”); out = new BufferedOutputStream(inner);

 

//write data to the file } catch (IOException e)

 

{

e.printStackTrace();

}

finally

{

try { out.close(); } catch (Exception e) {}

 

}


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Object Oriented Programming(OOP) : Java Exception Handling : Java I/O – The Basics |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.