finding IO #operations in #tough. this post will help you clear your doubts #jobseekers #freshers #java #javaforbeginners
From very early school days, we are familiar with writing notebooks and reading school books, novel, stories, etc. Keeping notes of important items help us remembering and planning our stuff. Similarly, we have files in java. Even java programs are files themselves. Files in java are made available through java.io.File package and java.io package contains literally everything needed for IO operations. IO operations are handled through Stream. A stream is a sequence of bytes and represents an input source and output source. Streams in java.io support almost all data types like primitives and objects.
STREAMS IN JAVA
A stream can be defined as a sequence of data. There are two types of streams
- InputStream: used to read data from the stream
- OutputStream: used to write/append data to stream
In the program, data flows in through inputStream and flows out using outputStream. Java has strong IO supports for both files and network IO operations.
STREAMS AVAILABLE IN JAVA
Byte Stream: byte stream contains byte as unit of data and all input/output operations are performed in the quantum of byte (8 bit). There is a number of implementations of BYTE STREAM but popularly used streams are FileInputStream and FileOutputStream. See the example below to understand byte streaming
import java.io.*; public class ByteStreamExample { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Above program reads byte by byte from file input.txt and writes data to output.txt. Once the reading/writing is done, both the files are closed in the finally{} clause.
Character Stream in Java
It reads two bytes at a time represent Unicode and writes two bytes of Unicode. The commonly used character stream implementations are FileReader and FileWriter. These wraps the FileInputStream and FileOutputStream respectively.
Standard Stream: Standard streams are used to take input from input peripheral devices like keyboard and writes to output devices like display of the computer. Every programming language provides supports for taking input from the keyboard and writing output to the computer display. Java provides 3 basic standard streaming implements:
- Standard Input: represented by Standard.in and used to provide input stream to computer programs.
- Standard Output: usually writes output to the computer screen. It is defined in Standard.out. It provides a standard output stream for computer output devices.
- Standard Error: used to display output error produced by computer programs. It is represented as Standard.error
Example of reading from the keyboard using standard input
import java.io.*; public class ReadFromKeyboard { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } } }
Above program goes on reading and once the user enters ‘q’ program exits.
INPUT-OUTPUT OPERATIONS ON FILES IN JAVA
IO on files are done using FileInputStream and FileOutputStream. Below image shows complete file io stream implementation in java.
FileInputStream: used to read data from the file. An object of FileInputStream can be created an either passing path of file or File object instance like below
InputStream f = new FileInputStream("C:/techandguru/file"); File f = new File("C:/techandguru/file"); InputStream f = new FileInputStream(f);
Methods provided by FileInputStream are listed in below table with description
Method Description public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file. public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream
FileOutputStream creates a file if not present and then opens the output stream to write data to the file. Like FileInputStream, FileOutputStream also has two constructors to create an object. Both are shown in the example
OutputStream f = new FileOutputStream("C:/techandguru/file") //take path to file File f = new File("C:/techandguru/file"); OutputStream f = new FileOutputStream(f); // takes File class object as argument
Methods and description of FileOutputStream Class
Method Description public void close() throws IOException{} This method closes the file output stream and flushes the data in the file. Releases any system resources associated with the file. Throws an IOException. protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. public void write(int w)throws IOException{} This method writes the specified byte to the output stream. public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream.
File, FileReader, FileWriter in Java
File class in java provides various utility methods to manage file and directories. The directory is a File which can contain other Directories and Files. File Class provides a way to create and list all directories of the given physical path on the machine.
File class provides mkdir() and mkdirs() methods to create the directory on the specified path in argument.
- mkdir() method is used to create a directory. It does not create a parent directory. It returns true on the successful creating directory and false otherwise. It could fail for various reasons like if permission is denied, if the path does not exist or if there is a directory already present.
- mkdirs() method is used to create directory and parent directories if not present.
- list() method is used to list all the files and directories on the specified path.
Below example list all the directories on the path “/temp”
import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create file object file = new File("/temp"); // list all files and directories on the path paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } } catch (Exception e) { // if any error occurs e.printStackTrace(); } } }
Java also provides an implementation for reading and writing character streams to files through FileReader and FileWriter. FileReader is implementation on InputStream and is used to read data from the file. FileWriter is implementation on OutputStream and is used to write character stream to files.














