Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Friday, October 30, 2015

Using Streams to Read and Write Files in Java


Streams are ordered sequences of data. 

Character Streams and Byte Streams

Consider the difference between Java source files and class files generated by the compiler. 
  • The Java source files have extension of .java and are meant to be read by humans as well as programming tools such as compilers. 
  • The Java class files have extension of .class and are not meant to be read by humans; they are meant to be processed by low-level tools such as a JVM . 
  • We refer to human-readable files containing text (or characters) as text files; we refer to the machine readable or low-level data storage files as binary files.

The java.io package has classes that support both character streams and byte streams. You can use character streams for text-based I/O. Byte streams are used for data-based I/O.
  • Character streams for reading and writing are called readers and writers, respectively (represented by the abstract classes of Reader and Writer). 
  • Byte streams for reading and writing are called input streams and output streams, respectively (represented by the abstract classes of InputStream and OutputStream).

Reading Text Files

Reader classes read the contents in the stream and try interpreting them as characters, such as a tab, end-of-file, newline, etc.


Reading and Writing Text Files

FileReader inputFile = new FileReader(file);
This uses unbuffered I/O, which is less efficient when compared to buffered I/O. In other words, the read characters are directly passed instead of using a temporary (internal) buffer, which would speed up the I/O. To programmatically use buffered I/O, you can pass the FileReader reference to a BufferedReader object.

BufferedReader inputFile = new BufferedReader(new FileReader(file);
In the same way, you can also use BufferedWriter for buffered output.

Copy.java
package com.appfworks.io;

/**
* Created by suresh on 30/10/15.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
// implements a simplified version of "copy" command provided in Windows
// syntax: java Copy SrcFile DstFile
// copies ScrFile to DstFile; over-writes the DstFile if it already exits
class Copy {
public static void main(String []files) {
if(files.length != 2) {
System.err.println("Incorrect syntax. Correct syntax: Copy SrcFile DstFile");
System.exit(−1);
}
String srcFile = files[0];
String dstFile = files[1];
// try opening the source and destination file
// with FileReader and FileWriter
try (BufferedReader inputFile = new BufferedReader(new FileReader(srcFile));
BufferedWriter outputFile = new BufferedWriter(new FileWriter(dstFile))) {
int ch = 0;
// while there are characters to fetch, read the characters from
// source stream and write them to the destination stream
while( (ch = inputFile.read()) != −1) {
// ch is of type int - convert it back to char before
// writing it
outputFile.write( (char)ch );
}
// no need to call flush explicitly for outputFile - the close()
// method will first call flush before closing the outputFile stream
} catch (FileNotFoundException fnfe) {
// the passed file is not found ...
System.err.println("Cannot open the file " + fnfe.getMessage());
}
catch(IOException ioe) {
// some IO error occurred when reading the file ...
System.err.printf("Error when processing file; exiting ... ");
}
// try-with-resources will automatically release FileReader object
}
}

No comments:

Post a Comment