How do I Copy files from one directory to another?

I know how to move files using the renameTo() method of File class, but is there a simple way to copy files, without the need of reading the input stream form one file and writing to a new one?

Hi all,
I ripped this off the jakarta-ant project's file copier (with a small tweak)..
package com.museumcompany.util;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
* This class also encapsulates methods which allow Files to be
* refered to using abstract path names which are translated to native
* system file paths at runtime as well as copying files or setting
* there last modification time.
* @author [email protected]
* @author Conor MacNeill
* @author Stefan Bodewig
* @version $Revision: 1.8 $
public class FileUtils {
private static Random rand = new Random(System.currentTimeMillis());
private static Object lockReflection = new Object();
* Factory method.
public static FileUtils newFileUtils() {
return new FileUtils();
* Empty constructor.
protected FileUtils() {}
* Convienence method to copy a file from a source to a destination.
* Overwrite is prevented, and the last modified is kept.
* @throws IOException
public void copyFile(String sourceFile, String destFile) throws IOException {
copyFile(new File(sourceFile), new File(destFile), false, true);
* Method to copy a file from a source to a
* destination specifying if
* source files may overwrite newer destination files and the
* last modified time of <code>destFile</code> file should be made equal
* to the last modified time of <code>sourceFile</code>.
* @throws IOException
public void copyFile(File sourceFile, File destFile,
boolean overwrite, boolean preserveLastModified)
throws IOException {
if (overwrite || !destFile.exists() ||
destFile.lastModified() < sourceFile.lastModified()) {
if (destFile.exists() && destFile.isFile()) {
destFile.delete();
// ensure that parent dir of dest file exists!
// not using getParentFile method to stay 1.1 compat
File parent = new File(destFile.getParent());
if (!parent.exists()) {
parent.mkdirs();
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[8 * 1024];
int count = 0;
do {
out.write(buffer, 0, count);
count = in.read(buffer, 0, buffer.length);
} while (count != -1);
in.close();
out.close();
if (preserveLastModified) {
destFile.setLastModified(sourceFile.lastModified());
public File createTempFile(String prefix, String suffix, File parentDir) {
File result = null;
DecimalFormat fmt = new DecimalFormat("#####");
synchronized (rand) {
do {
result = new File(parentDir,
prefix + fmt.format(rand.nextInt())
+ suffix);
} while (result.exists());
return result;

Similar Messages

  • How do you copy files from one user to another

    How do you copy files from one user to another user on the same machine?

    open your home folder in finder move file to public, log into other account, click the go tab on the finder menu, select computer, your hard drive (Macintosh HD Default)>Users, the origonal user> public and drag that file to your specified folder.
    hope it works
    Craig.

  • Java Program to copy file from one directory to another failing

    Hello All,
    Oracle Applications 12.1.3
    RDBMS: 11.2.0.30
    SQL*Plus: 10.1.0.5.0
    Java beginner here so help is much appreciated.  I'm have some java code that I'm using to copy a file from one directory to another in an Oracle Applications Server.  I notice that when moving to a new instnace I started to get file not found errors.  I think it's because of the directory.  My question is, does the directory in which I trying to pick up the file have to be a DBA_DIRECTORY, or a UTL_FILE directory in order for the java to find the file and move it?
    Here is my code...
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "COPY_FILE_JVS" AS
    import java.io.*;
    public class COPY_FILE_JVC{
      public static void copy(String SourceFile, String DestDir) {
        File source = new File(SourceFile);
        File dest = new File(DestDir);
        File cpDestFile = null;
        try {
          if (dest.isDirectory()) {
              if(source.isFile()) {
                System.out.println("File name = " + source.getName());
                System.out.println("File name dest = " + dest.getPath() );
                System.out.println("File name cpDestFile = " + dest.getPath() + File.separator + source.getName());
                cpDestFile = new File(dest.getPath() + File.separator + source.getName());
              else {
                System.out.println("Directory or File Not Found");
                return;
          BufferedInputStream  br = new BufferedInputStream (new FileInputStream (source));
          BufferedOutputStream  bw = new BufferedOutputStream (new FileOutputStream (cpDestFile));
          int read = 0;
          while((read = br.read()) != -1) {
            //System.out.println((char)read);
            bw.write(read);
          br.close();
          bw.close();
        catch (FileNotFoundException e) {
        e.printStackTrace();
        catch (IOException e) {
        e.printStackTrace();

    I get these messages when calling the java from SQL Plus as follows...
    serveroutput on size 100000;
    dbms_java.set_output(1000000);
    MY_PKG.CopyFile('/home/my_user/set_env.sh','/interface/home'); (this is call to oracle pl/sql package which calls the java.)
    PL/SQL procedure successfully completed.
    Directory or File Not Found
    PL/SQL procedure successfully completed.
    If I change the directory from /home/my_user/ to any directory that is defined in DBA_DIRECTORIES or is a UTL_FILE directory to program works.  Is it perhaps because the java is in a PL/SQL package as seen below?  The PL/SQL program runs as the APPS user and I have issued the following the command grant JAVASYSPRIV to APPS.
    Here is the PL/SQL Package....
    CREATE OR REPLACE PACKAGE BOLINF.MY_PKG AUTHID CURRENT_USER AS
    CopyFile(p_SourceFile IN VARCHAR2, p_DestDir IN VARCHAR2);
    +++++++++++++++++++++++++++++
    CREATE OR REPLACE PACKAGE BODY BOLINF.MY_PKG  is
    CopyFile(p_SourceFile IN VARCHAR2, p_DestDir IN VARCHAR2)
    AS LANGUAGE JAVA NAME 'COPY_FILE_JVC.copy(java.lang.String, java.lang.String)';

  • How to Move  a file from one Directory to another directory.

    Hi All
    i am having a Java standlone Application reqiurements are
    1---->Connection pool To be Created.
    2---->Using Thread to read Multiple Files Simulatneously.
    3----->After Reading Those file I have to Move it to another folder.
    Plz help me.If possible give me sample code .
    I am in deep trouble for this project.

    Use java.io.File.renameTo(...) (look it up in the API documentation).
    Renaming a file doesn't work if you're trying to move files from one disk to another disk. In that case, you have to copy the file and delete the original.

  • How can i copy files from one external hard disk to another using macbook pro with retina display

    How can i copy files from one external hard drive to another using macbook pro with retina display?

    That's odd - if you open Disk Utility (Applications->Utilities) and select the disk(s), how are they formatted? If you're only going to be used with your Mac, they should be formatted as "Mac OS Extended (Journaled)".
    Clinton

  • How do i move a file from one directory to another?

    Can anyone help me in moving a file from one directory to another?
    The following code just does not work!!
    File source_file = new File(source_file);
    if(source_file.exists())
    File dest_file = new File(destination_file);
    if(!dest_file.exists())
    boolean moved = source_file.renameTo(dest_file);
    System.out.println("moved.."+moved);
    The varirable moved is always false.
    Can anyone tell me whts wrong in this code?

    The problem in your code is you used file object as argument when you create a new File. I changed a little bit codes and it should be fine now.
    String source_file1="test111.txt";
    String destination_file1="test222.txt";
    try{
         File source_file = new File(source_file1);
         if(source_file.exists())
              File dest_file = new File(destination_file1);
              if(!dest_file.exists())
                   boolean moved = source_file.renameTo(dest_file);
                   System.out.println("moved.."+moved);
    catch(Exception e){
               e.printStackTrace();
    }

  • How can i copy apps from one computer to another?

    how can i copy apps from one computer to another?

    You don't mention which operating system you have so it's difficult to provide an answer since the mac and Windows stores the files differently.
    The other thing you can do is just re-download the apps from the iTunes Store. Just login to the iTunes Store on the other computer using the same Apple ID. On the right-hand side of the iTunes Store page you will see a 'Purchased' link. Clicking on that will take you to a page that will list your past purchases which you can re-download to the new computer.

  • Ssis - move files from one directory to another and rename destination file if present

    Hello,
    How is it possible to move files from one directory to another directory and if the file already exists in destination directory then rename it?
    Thanks

    1. Use a foreach loop with file enumerator pointing to first directory.
    Inside loop have a ssis variable of type string to get filename (@[User::FileName])
    Choose option as Fully Qualified in loop
    2. Add another variable called @[User::DestFileName], set EvaluateAsExpression true for it and set expression like this
    REPLACE(@[User::FileName],<source directory path>,<destination directory path>)
    put actual paths in above expression in your case
    and another variable called @[User::RenameFileName], set EvaluateAsExpression true for it and set expression like this
    REPLACE(@[User::FileName],".","_old.")
    3. Create a boolean variable say @[User::FileEXists]
    4. Add a Script Task inside the loop and pass @DestFileName variable in ReadOnly mode and FileExists in ReadWrite mode
    Inside Script Task write code as per below
    http://blog.dbandbi.com/2013/11/13/check-file-exists-ssis/
    5. Add File System Task choose operation as Rename File, Select IsSourcePathVariable as true and select @[user::DestFileName] variable and IsDestinationPath variable as true and select @[user::RenameFileName] variable
    6. Choose ExpressionAndConstraint option for precedeence constraint from ScriptTask to above File System Task and choose constraint as OnSuccess and expression as
    @FileExists == True
    7. Add another File System task with operation as Move File Select IsSourcePathVariable as true and select @[user::FileName] variable and IsDestinationPath variable as true and select @[user::DestFileName] variable. Join Script Task as well as
    File System Task above to this task and choose constraint as OnSuccess and Multiple Constraint option as Or (dotted line)
    Then once executed it will work as per your requirement
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How do I move files from one album to another?

    How can I move files from one album to another? And why does itunes split up imported folders?

    Press the Command key while dragging them.
    (58054)

  • How can I copy text from one card to another while creating cards using Iphoto?

    I created two cards with different pictures using Iphoto on Macnotebook. 
    I want to use the same text message.
    How can I copy text from one card to another?

    select the text and copy (edit menu ==> copy) tehn gpo to the next card and paste
    LN

  • How do I copy text from one layer to  another?

    I have Googled this but not a single answer seems to work.
    I am using Photoshop CS4 on OS X 10.6.7.
    OK, so  I  have a layer that  has some text in it.  I would like to  be able to  simply copy that  text  from one layer  to  another, but this seems to  be impossible as the Edit Paste menu item is grayed out after I have copied it in to the clipboard.  I can paste it into  the SAME layer, but not into another layer.
    This is how I am trying to  do  this.
    In the layer  with the text, click on the "T" icon to  the left.
    Click on the text, in the layer that I  want to  copy. 
    I select the text (either  by  clicking and dragging or pressing Command-A).
    Next I press Command-C.
    Then I  click on the layer In the Layer Panel) where I want to  paste the text.
    Pressing Command-V is impossible because the Edit-Paste menu option is grayed out!!!!
    WHY??????
    Perhaps more importantly, HOW do I copy text  from one layer to  another?

    First thing you can simply right click on the Text Layer and choose Duplicate Layer.  But that will create a new Text Lay
    er identical to the one you have.
    To answer your question in your case....  Create the Text Layer.   Make a New Layer.  Or have the layer you want to paste into visible.
    Highlight the text layer in the Layer Palette and Ctrl+Click (Win) Cmd+Click(Mac) so that you see marching ants walking around your text.
    Edit>Copy.
    Then highlight your Layer you want to paste into and hit Edit>Paste or Cmd+V / Ctrl+V.

  • HT3819 how do I copy songs from one ipod to another

    How do I copy songs from one ipod to another?

    Transfer the songs to iTunes and then sync to the other iPod.

  • How do I transfer files from one computer to another without using cables??

    How do I transfer files from one computer to another without using cables?

    Wifi network
    Email
    Thumb Drive
    Online storage such as, iCloud Google Docs, SkyDrive, etc.

  • How do I copy photos from one iPad to another iPad?

    How do I copy photos from one ipad to another ipad without using my Mac?

    https://appsto.re/us/SQ8Wv.i
    This app helps you to upload easy all you photos by selecting all
    to your dropbox account,
    to Google Drive,
    To your computer,
    to another device,

  • How do i copy music from one ipod to another with 1 cord?

    how do i copy music from one ipod to another with 1 cord?

    You cannot copy content directly from one iPod to another. If the music was purchased from the iTunes Store, you have the following options:
    - sync the iPod to your computer, transfer the content to iTunes, and then connect the other iPod and sync from iTunes
    - use iCloud (which requires iOS 5).
    - download the music from from the iTunes Store to the second iPod. See:
    http://support.apple.com/kb/ht2519
    Regards.
    Message was edited by: varjak paw

Maybe you are looking for

  • Office 2013 templates Group Policies

    There is a GPO related to Enterprise template locations in Office 2013 that is not clear at all and poorly documented. The path to the GPO is:  MS Office 2013 > Shared Paths > Enterprise templates path What is the purpose and how this path can be use

  • INTEGRATION_CIRECTORY_HMI

    Hi, My INTEGRATION_DIRECTORY_HMI  RFC dest is not working.. as somebody has specified a different user..now when i specify PIISUSER it asks me pwd..how can i get this pwd for PIISUSER also what path prefix do i need to give when recreating this INTEG

  • How to edit the binding wsdl link in SR

    Hello, I have created a WS which uses my server name : and port, further service name and ?wsdl. well actually my server full name is ???.??.de and I am using my server from laptop. If I use SR from other computer and try to see the wsdl file there b

  • Comma prompt error in datagrid

    I had created a timetable in the datagrid. The datagrid is able to display individual staff's tiimetable. However, I was prompt an error when I click on this particular staff to view the class schedule. I found out that the error is caused by a comma

  • Help with Photoshop CS5 update?

    I operate in Windows 7. Have been unsuccessful in updating. I keep getting error message serial number is not eligible. Can't understand the instructions on the page that lists this as a common problem. Please help.