Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML

Search:
   Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML Facing Programming Problem? Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
Java - Copying one file to another
In this section, you will learn how to copy contents from one file to another file.
 
 

Java - Copying one file to another

                         

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:

  1. An optional system-dependent prefix string,
    such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
  2. A sequence of zero or more string names.

Explanation

This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.

copyfile(String srFile, String dtFile)

The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(srFile);
File f2 = new File(dtFile); 

and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2); 

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.

// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);

Code of the Program : 

import java.io.*;

public class CopyFile{
  private static void copyfile(String srFile, String dtFile){
    try{
      File f1 =
 new File(srFile);
      File f2 = new File(dtFile);
      InputStream in = new FileInputStream(f1);
      
      //For Append the file.
//      OutputStream out = new FileOutputStream(f2,true);

      //For Overwrite the file.
      OutputStream out = new FileOutputStream(f2);

 
     byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0){
        out.write(buf, 0, len);
      }
      in.close();
      out.close();
      System.out.println(
"File copied.");
    }
    catch(FileNotFoundException ex){
      System.out.println(ex.getMessage() + " in the specified directory.");
      System.exit(
0);
 
   }
    catch(IOException e){
      System.out.println(e.getMessage());      
    }
  }
  public static void main(String[] args){
    switch(args.length){
      case 0: System.out.println("File has not mentioned.");
   
       System.exit(0);
      case 1: System.out.println("Destination file has not mentioned.");
 
         System.exit(0);
      case 2: copyfile(args[0],args[1]);
          System.exit(0);
      default : System.out.println("Multiple files are not allow.");
            System.exit(0);
    }
  }
}

Download File Copy Example

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

11 comments so far (
post your own) View All Comments Latest 10 Comments:

How to pass the username and password from java file to j_security_check.

Posted by ilango on Monday, 07.7.08 @ 18:16pm | #66159

Iam asking How to copy a file as word document from any format(ex:txt,png,jpeg....)

Posted by anithavelde on Friday, 04.25.08 @ 12:41pm | #57839

I want to copy a file as word document from any format of file. please give the solution for my problem and send the solution to my ID

Posted by anitha on Wednesday, 04.23.08 @ 17:38pm | #57698

I'm having trouble with this problem written below, can somebody help me ? Please, I need it badly. I know there's a lot of java genius out there...

Write a java program that will be able to:
a. read text line by line;
b. create a directory;
c. delete files from the directory;
d. list the contents of the directory;
e. copy the contents of the file from one file to another; and

f.write text to a file (character output stream)

Posted by Odessy (student) on Sunday, 10.14.07 @ 14:30pm | #33809

i am proud of this website.

Posted by Yuran on Saturday, 10.13.07 @ 10:09am | #33464

hi,


ive run the sample program and i get the output that the file is not mention,,so for example which part of the program can i actually input the file to be copied and how can i check if the file has been copied...and lastly what file are we trying to copy here...

Posted by gina esteban on Saturday, 07.28.07 @ 14:00pm | #22101

Excellent and easily understandable tutorial

Posted by hari on Tuesday, 06.5.07 @ 17:15pm | #18284

George,
at the command line type:
java CopyFile file1.txt file2.txt

where file1.txt and file2.txt are your source(sr) and destination(dt) files.

The contents of file1.txt will now be copied into the contents of file2.txt

Posted by tivup on Sunday, 04.1.07 @ 04:36am | #13104

when tryin to run the file to file copy code.
am gettin an errer ; File has not mentioned.
But i created 2 files seperately nd renamed f1 nd f2 with those file names . still not workin ..
kindly help....

Posted by George on Friday, 03.23.07 @ 15:49pm | #12559

very good website for begineers
and its realy cool and simple

Posted by binu on Monday, 02.19.07 @ 17:17pm | #8386

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.