2 Replies Latest reply: Apr 3, 2013 10:26 AM by 836548 RSS

    How to copy file from  one location to another

    BK574
      Hi,

      I am new to java, I tried the following code to move the file from one location to another
      public class CopyFiles {
      public String copy ( File source, File target)
      throws IOException {   
      FileChannel sourceChannel = null;
      FileChannel targetChannel =null;
      try {   
      sourceChannel =new FileInputStream(source).getChannel();
      targetChannel= new FileOutputStream(target).getChannel();
      targetChannel.transferFrom(sourceChannel, 0,
      sourceChannel.size());
      }
      finally {   
      targetChannel.close();
      sourceChannel.close();
      }
      return "Success";
      }

      public static void main(String [] args) throws Exception{   

      File source = new File("C:\\users\\download.pdf");
      File destinationFile = new File("C:\\apple\\download.pdf");
      copy(source, destinationFile);
      }
      }

      The above code is working perfectly, but I Don't want to include the file name in destination file. i.e. File destinationFile=new File("C:\\apple"), and at the same time the pdf with same name has to get stored in the destination location, how can I achieve this.
        • 1. Re: How to copy file from  one location to another
          973635
          kameshb wrote:
          I Don't want to include the file name in destination file. i.e. File destinationFile=new File("C:\\apple"), and at the same time the pdf with same name has to get stored in the destination location, how can I achieve this.
          It's not totally clear what you're saying here, but what I think you mean is that you don't want to explicitly set the destination file name--you want to just give the copy the same name as the original. Yes?

          If that's the case, then break the original up into separate directory and file name portions, and then construct the destination path from the destination directory plus original file name. You can do that by manipulating the full path string, or by using the methods in java.io.File.
          • 2. Re: How to copy file from  one location to another
            836548
            if you don't want to give file names run time including absolute path, then you can do so by passing the same as arguments (command line arguments) to your program.