What is Java I/O
Java IO is an API that comes with Java which is targeted at reading and writing data (input and output).
Most applications need to process some input and produce some output based on that input.
For instance, read data from a file or over network, and write to a file or write a response back over the network.
Java performs I/O through Streams.
What is Stream in Java?
A stream can be defined as a sequence of data.
Java encapsulates Stream under java.io package.
Java defines two types of streams. They are,
- Byte Stream
- Character Stream
Byte Stream
Byte streams process data byte by byte.
Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.
Stream class | Description |
---|---|
InputStream | InputStream is used to read data from a source. |
OutputStream | OutputStream is used for writing data to a destination. |
BufferedInputStream | Used for Buffered Input Stream. |
BufferedOutputStream | Used for Buffered Output Stream. |
DataInputStream | Contains method for reading java standard datatype |
DataOutputStream | An output stream that contain method for writing java standard data type |
FileInputStream | Input stream that reads from a file |
FileOutputStream | Output stream that write to a file. |
PrintStream | Output Stream that contain print() println() method |
How to write byte content to a file in java?
When you are dealing with bytes, you need to use Streams.
Example:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; class ByteWriteToFile { public static void main(String[] args) throws IOException { OutputStream opStream = null; try { String strContent = "This example shows how to write byte content to a file"; byte[] byteContent = strContent.getBytes(); File myFile = new File("C:/hsss.txt"); opStream = new FileOutputStream(myFile); opStream.write(byteContent); opStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally{ opStream.close(); } } }
How to read file content using InputStream?
Example:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; class FileToByteArray { public static void main(String a[]) throws IOException{ String fileName = "C:/hsss.txt"; InputStream is = null; try { is = new FileInputStream(fileName); byte content[] = new byte[100]; int readCount = 0; while((readCount = is.read(content)) > 0){ System.out.println(new String(content, 0, readCount-1)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try{ if(is != null) is.close(); } catch(Exception ex){ } } } }
Character Stream
In Java, characters are stored using Unicode conventions.
Character stream automatically allows us to read/write data character by character.
Character stream is defined by using two abstract class at the top of hierarchy, they are Reader and Writer.
Stream class | Description |
---|---|
Reader | Abstract class that define character stream input |
Writer | Abstract class that define character stream output |
BufferedReader | Handles buffered input stream. |
BufferedWriter | Handles buffered output stream. |
FileReader | Input stream that reads from file. |
FileWriter | Output stream that writes to file. |
InputStreamReader | Input stream that translate byte to character |
OutputStreamReader | Output stream that translate character to byte. |
PrintWriter | Output Stream that contain print() println() method. |
How to read the character using Streams?
read() method is used with Reader object to read characters. As this function returns integer type value has we need to use typecasting to convert it into char type.
Syntax
int read() throws IOException
Example:
class CharRead{ public static void main( String args[]) throws IOException{ InputStreamReader br = new InputStreamReader(System.in); System.out.println("Enter character:"); char c = (char)br.read(); //Reading character System.out.println("Your character is:"+c); } }
How to write string content to a file in java?
When you are dealing with characters, you need to use Writer.
Example:
import java.io.File; import java.io.FileWriter; import java.io.IOException; class WriteToFile { public static void main(String[] args) throws IOException { FileWriter writer = null; try { String strContent = "This example shows how to write string content to a file"; File myFile = new File("C:/hsss.txt"); writer = new FileWriter(myFile); writer.write(strContent); } catch (IOException e) { e.printStackTrace(); } finally{ writer.close(); } } }
How to write string content to a file using BufferedWriter?
We have to bind BufferedWriter in FileWriter.
Example:
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; class Writing_Test { public static void main(String [] args){ String fileName = "C:/hsss.txt"; try { FileWriter fileWriter =new FileWriter(fileName); BufferedWriter bufferedWriter =new BufferedWriter(fileWriter); bufferedWriter.write("Hello there,"); bufferedWriter.write(" here is some text."); bufferedWriter.newLine(); bufferedWriter.write("We are writing"); bufferedWriter.write(" the text to the file."); bufferedWriter.close(); }catch(IOException ex){ System.out.println("Error writing to file '" + fileName ); } } }
How to read file content line by line in java?
To get this, you have to use BufferedReader object.
By calling readLine() method you can get file content line by line.
readLine() returns one line at each iteration, we have to iterate it till it returns null.
Example:
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; class ReadLinesFromFile { public static void main(String a[]){ BufferedReader br = null; String fileName = "C:/hsss.txt"; String line = ""; try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { System.err.println("Unable to find the file: fileName"); } catch (IOException e) { System.err.println("Unable to read the file: fileName"); } } }
Is it Possible to bind the FileReader in BufferedReader?
Yes,We can bind the FileReader in BufferedReader.
Example:
class ReadLinesFromFile { public static void main(String a[]){ BufferedReader br = null; String fileName = "C:/hsss.txt"; String line = ""; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { System.err.println("Unable to find the file: fileName"); } catch (IOException e) { System.err.println("Unable to read the file: fileName"); } } }
How to read input from java console in java?
We have to pass System.in object to InputStreamReader class.
Create BufferedReader object by passing InputStreamReader, readLine() method can helps you to get the typed commands.
Example:
import java.io.BufferedReader; import java.io.InputStreamReader; class ReadLineFromConsoleExample { public static void main(String[] args) { BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); String strLine = null; System.out.println("Reading line of characters from console"); System.out.println("Enter exit to quit"); try{ while( (strLine = br.readLine()) != null){ if(strLine.equals("exit")) break; System.out.println("Line entered : " + strLine); } br.close(); } catch(Exception e){ System.out.println("Error while reading line from console : " + e); } } }
Solve this!!
InputStream & OutputStream classes under byte stream they are not streams. Character Stream contains all the classes which can work with Unicode.
- Collection
- ArrayList
- LinkedList
- Vector
- HashSet
- Conditional Statements
- Classes and Objects
- Inheritance
- Packages
- Exception Handling
- Threads
- TreeSet
- LinkedHashSet
- HashMap
- TreeMap
- LinkedHashMap
- HashTable
- Iterator and ListIterator
- String
- Scanner
- Array Small Programs
- Introduction
- Variables
- DataTypes
- Operators
- Conditional Statements
- Loop
- Arrays
- Object Oriented Programming
- Classes and Objects
- Access Modifiers
- Methods
- Abstraction
- Constructor
- Packages
- StringBuffer
- Inheritance
- StringBuilder
- Encapsulation
- Java IO
- Polymorphism
- Interface
- Types Of Variables
- Static Keyword
- Final Keyword
- Super Keyword
- This Keyword
- Exception Handling