Copying data from one file to other file using java

Before to this post we have learnt about writing data to a File and reading data from the File.In our today’s post we shall learn about copying the data from one File to the other File.This is pretty easy and we shall use the same concepts which we have discussed till now.

To copy the data from a file,first we need to open the file in reading mode(as input).Now we shall read all the data present in the file and store it in a byte array.We need to open the destination or target file in writing mode and we shall write the data present in the byte array into the target file.

import java.io.*;
class filecopy
{
	public static void main(String arg[])
	{
		try
		{
			FileInputStream fis = new FileInputStream("source.txt");
			int size = fis.available();
			char ch[] = new char[size]; 
			String str[] = new String[size];
			for(int i=0;i<size;i++)
			{
				ch[i] = (char)fis.read();
			}
			FileOutputStream fos = new FileOutputStream("destination.txt");
			byte b[] = new byte[ch.length];
			for(int i=0;i<size;i++)
			{
				b[i] = (byte) ch[i];
				fos.write(b[i]);
			}	
			fos.close();		
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}

Output:
java_filecopy_01
filecopy_source
file_copy_dest

Download the source code!

Advertisements

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my Master's in Computer Science.
This entry was posted in Java and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s