Share on Google+Share on Google+

How to write content of one file to another file.

This tutorial demonstrate how to write content of one file to another file using CheckedOutputStream class.

CheckedOutputStream Example

In this example, we will  discuss about the use of CheckedOutputStream class. The CheckedOutputStream class is from the package. The CheckedOutputStream  class is used to compute the checksum of the data being written on the output stream. 

In this example we will open a file and then write the content in new file. And at the same time the CheckedOutputStream  class calculates checksum of the data being written in the second file.

About CheckedOutputStream class:

The class extends CheckedOutputStream class. It provides the following methods:

Return type Method Description
Checksum getChecksum()  Function returns the checksum of the associated steam.
void write(byte[] b, int off, int len) The write(..) method writes an array of bytes onto the associated stream.
void write(int b) Method writes one byte of data onto the stream

Here is the example code that writes the data into second file and also calculates and report the checksum with the help of CheckedOutputStream class.


public class CheckWriteDemo1 {
  public static void main(String args[]) {

    String newfile = "newtestfile.txt";
    String oldfile = "oldtestfile.txt";
    byte[] b = new byte[1024];
    try {
      FileOutputStream fileoutStream = new FileOutputStream(newfile);
      CheckedOutputStream outstream = new CheckedOutputStream(fileoutStream,
          new CRC32());
      FileInputStream inStream = new FileInputStream(oldfile);
      int length;
      while ((length = > 0) {
        outstream.write(b, 0, length);

      System.out.println("The value of CRC32 Checksum is : "
          + outstream.getChecksum().getValue());
      .println(" Content of one file successfully written in other file  ");
    catch (IOException ioe) {

      System.out.println("IOException : " + ioe.getMessage());


Following is the output if you run the application:

C:\>java CheckWriteDemo1
The value of CRC32 Checksum is : 1836825431
Content of one file successfully written in other file

Download Source Code



Posted on: July 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null