BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Copy a File to another File in Java

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial we will see how to copy the content of one file to another file in java. In order to copy the file, first we can read the file using FileInputStream and then we can write the read content to the output file using FileOutputStream.

Example

The below code would copy the content of “MyInputFile.txt” to the “MyOutputFile.txt” file. If “MyOutputFile.txt” doesn’t exist then the program would create the file first and then it would copy the content.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class CopyExample 
{
    public static void main(String[] args)
    {	
    	FileInputStream instream = null;
	FileOutputStream outstream = null;
 
    	try{
    	    File infile =new File("C:\\MyInputFile.txt");
    	    File outfile =new File("C:\\MyOutputFile.txt");
 
    	    instream = new FileInputStream(infile);
    	    outstream = new FileOutputStream(outfile);
 
    	    byte[] buffer = new byte[1024];
 
    	    int length;
    	    /*copying the contents from input stream to
    	     * output stream using read and write methods
    	     */
    	    while ((length = instream.read(buffer)) > 0){
    	    	outstream.write(buffer, 0, length);
    	    }

    	    //Closing the input/output file streams
    	    instream.close();
    	    outstream.close();

    	    System.out.println("File copied successfully!!");
 
    	}catch(IOException ioe){
    		ioe.printStackTrace();
    	 }
    }
}

Output:

File copied successfully!!

The methods used in the above program are:

read() method

public int read(byte[] b) throws IOException

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. It returns total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. In order to make this method work in our program, we have created a byte array “buffer” and reading the content of input file to the same. Since this method throws IOException, we have put the “read file” code inside try-catch block in order to handle the exception.

write() method

public void write(byte[] b,
                  int off,
                  int length)
           throws IOException

Writes length bytes from the specified byte array starting at offset off to this file output stream.

Tweaks:
If your input and outfile files are not in the same drive then you can specify the drive while creating the file object. For example if your input file is in C drive and output file is in D drive then you can create the file object like this:

File infile =new File("C:\\MyInputFile.txt");
File outfile =new File("D:\\MyOutputFile.txt");

Top Related Articles:

  1. How to get the last modified date of a file in java
  2. How to get current day, month, year, day of week/month/year in java
  3. Java Exception Handling Examples
  4. What is break Keyword in Java
  5. How to read file in Java using BufferedReader

Tags: Java-IO

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Chandan Manna says

    January 8, 2015 at 8:18 PM

    Learn things very smoothly. Very helpful. Please post something on Design Pattern.

    Reply
  2. Sandipan Singha says

    February 15, 2017 at 11:31 AM

    instream.close(),outstream.close() these two statements should be finally() block.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap