Home Tutorial Java Corejava Zip How to write content of one file to another file.

 
 

Share on Google+Share on Google+
How to write content of one file to another file.
Posted on: July 12, 2010 at 12:00 AM
Advertisement
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 java.util.zip 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 java.util.zip.CheckedOutputStream 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.

import java.io.*;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.CheckedOutputStream;

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 = inStream.read(b)) > 0) {
        outstream.write(b, 0, length);
      }

      System.out.println("The value of CRC32 Checksum is : "
          + outstream.getChecksum().getValue());
      System.out
      .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

Advertisement

Related Tags for How to write content of one file to another file.:


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.

Posted on: July 12, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com