Monday, June 1, 2015

Character Streams

package characterStream;

// Character Streams are used to perform input and output for 16-bit unicode
// Though there are many classes related to character streams but the most frequently used
// classes are , FileReader and FileWriter..
// Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
//  here major difference is that FileReader reads two bytes at a time and FileWriter writes
//   two bytes at a time.

// NOTES:
// Now let's have a file input.txt with the following content: "This is test for copy file".

// In this case the file is made inside outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.


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

public class CharacterStream {

public static void main(String[] args) throws IOException{
FileReader fr = null;
FileWriter fw = null;

try {
fr = new FileReader("src/input.txt");
fw = new FileWriter("output.txt");
// in this case the out file is made below the system JRE files

int c;

while((c = fr.read()) != -1){
fw.write(c);
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fr != null){
fr.close();
}
if(fw != null){
fw.close();
}
}
}
}

-------------------------------------------input.txt------------------------------------------

This is test for copy file.

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

  // In this case the file is made inside outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file. 


No comments:

Post a Comment