Wednesday, September 2, 2015

Character Stream

------------------------------Main.java-------------------------

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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

// Stream is used to perform input and output of 16-bit unicode.
// FileReader use the FileInputStream and FileWriter uses the FileOutputStream.
// FileReader read two byte at a time and FileWriter write two byte at a time.

FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int readChar;
while((readChar = in.read()) != -1){
out.write(readChar);
}
System.out.println("\nSuccessfully copied/write the text of input.txt to the output.txt file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}

--------------------------OUTPUT----------------------

Byte Streams

-------------------------Main.java------------------

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main
{
public static void main(String[] args) throws IOException
{
// Stream represents the input source and output destination
// InputStream is used to read data from the source and
// OutputStream is used to write data to the destination

// Byte Stream is used to perform input and output of 8-bit byte

FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("input.txt");
fileOutputStream = new FileOutputStream("output.txt");

int text ;
while((text = fileInputStream.read()) != -1){
fileOutputStream.write(text);
// Copying the text value of input.txt to output.txt
}
System.out.println("\nSuccessfully copied the text of input.txt to the output.txt file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileInputStream != null){
fileInputStream.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
}
}
}

---------------------Output----------------------