Java Code to Move file from Desktop to Application Server Directory


Good Morning, I need your help in the following scenario.

I have xml, html and some javascript in my desktop. I wanted to Move this files to the server (say IIS Server). I can manually do it. But, we quiet often change this file and publish to the server.

Can somebody help me create the Java class to move the file from one place(eg desktop) to the server. If somebody, already developed this code, please let me know.

I truly appreciate your help.

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can use this class to shift them:

// This example is from _Java Examples in a Nutshell_. (
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see


 * This class is a standalone program to copy a file, and also defines a
 * static copy() method that other programs can use to copy files.
public class FileCopy {
  /** The main() method of the standalone program.  Calls copy(). */
  public static void main(String[] args) {
    if (args.length != 2)    // Check arguments
      System.err.println("Usage: java FileCopy <source file> <destination>");
    else {
      // Call copy() to do the copy, and display any error messages it throws.
      try { copy(args[0], args[1]); }
      catch (IOException e) { System.err.println(e.getMessage()); }

   * The static method that actually performs the file copy.
   * Before copying the file, however, it performs a lot of tests to make
   * sure everything is as it should be.
  public static void copy(String from_name, String to_name) throws IOException{
    File from_file = new File(from_name);  // Get File objects from Strings
    File to_file = new File(to_name);
    // First make sure the source file exists, is a file, and is readable.
    if (!from_file.exists())
      abort("FileCopy: no such source file: " + from_name);
    if (!from_file.isFile())
      abort("FileCopy: can't copy directory: " + from_name);
    if (!from_file.canRead())
      abort("FileCopy: source file is unreadable: " + from_name);
    // If the destination is a directory, use the source file name
    // as the destination file name
    if (to_file.isDirectory())
      to_file = new File(to_file, from_file.getName());
    // If the destination exists, make sure it is a writeable file
    // and ask before overwriting it.  If the destination doesn't
    // exist, make sure the directory exists and is writeable.
    if (to_file.exists()) {
      if (!to_file.canWrite())
        abort("FileCopy: destination file is unwriteable: " + to_name);
      // Ask whether to overwrite it
      System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
      // Get the user's response.
      BufferedReader in=new BufferedReader(new InputStreamReader(;
      String response = in.readLine();
      // Check the response.  If not a Yes, abort the copy.
      if (!response.equals("Y") && !response.equals("y"))
        abort("FileCopy: existing file was not overwritten.");
    else {  
      // if file doesn't exist, check if directory exists and is writeable.
      // If getParent() returns null, then the directory is the current dir.
      // so look up the user.dir system property to find out what that is.
      String parent = to_file.getParent();  // Get the destination directory
      if (parent == null) parent = System.getProperty("user.dir"); // or CWD
      File dir = new File(parent);          // Convert it to a file.
      if (!dir.exists())
        abort("FileCopy: destination directory doesn't exist: " + parent);
      if (dir.isFile())
        abort("FileCopy: destination is not a directory: " + parent);
      if (!dir.canWrite())
        abort("FileCopy: destination directory is unwriteable: " + parent);
    // If we've gotten this far, then everything is okay.
    // So we copy the file, a buffer of bytes at a time.
    FileInputStream from = null;  // Stream to read from source
    FileOutputStream to = null;   // Stream to write to destination
    try {
      from = new FileInputStream(from_file);  // Create input stream
      to = new FileOutputStream(to_file);     // Create output stream
      byte[] buffer = new byte[4096];         // A buffer to hold file contents
      int bytes_read;                         // How many bytes in buffer
      // Read a chunk of bytes into the buffer, then write them out,
      // looping until we reach the end of the file (when read() returns -1).
      // Note the combination of assignment and comparison in this while
      // loop.  This is a common I/O programming idiom.
      while((bytes_read = != -1) // Read bytes until EOF
        to.write(buffer, 0, bytes_read);            //   write bytes
    // Always close the streams, even if exceptions were thrown
    finally {
      if (from != null) try { from.close(); } catch (IOException e) { ; }
      if (to != null) try { to.close(); } catch (IOException e) { ; }

  /** A convenience method to throw an exception */
  private static void abort(String msg) throws IOException {
    throw new IOException(msg);
For the target directory, you can UNC notation


The source directory will be



The source directory will be


should have been

System.getProperty("user.home") + "\\Desktop";
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

alagappanKAuthor Commented:
Can you please eloborate on the source and destination. I have a directory called   c:\MyProject and this directory contains many sub-directory and the which contains the xml, html and javascript.

In this case, I just pass the source as  c:\MyProject  ???

Destination, what you mean by UNC notation and can you please eloborate and explain it a bit.

I truly appreciate CEHJ

Yes. The code simply copies one file at a time so you will have to iterate the source directory and call the function. THe UNC notation is simply a way of naming files on a network.


gives the format. Of course, you willhave to *have* a share (share_name) on the target machine over the network
alagappanKAuthor Commented:
Here is my source directory structure looks like

                    whxdata (it contains all xml files)
                    whxdata (another set of xml files)

How do I copy all this directory structure into Server. Would you please give me the code for copying the whole directory structure and the file.

I really appreciate your help,
thank you,
You can use this to call it:


class FileCopyRecurse {
  private FileFilter filter;
  private String sourceDir;
  private String targetDir;

  public FileCopyRecurse(String sourceDir, String targetDir) {
    this.sourceDir = sourceDir;
    this.targetDir = targetDir;
    filter = new XmlOnly();

  public static void main(String[] args) {
    // Check the arguments if you're going to use main
    FileCopyRecurse fc = new FileCopyRecurse(args[0], args[1]);
    try {
    } catch (IOException e) {

  public void copyAll() throws IOException {
    File source = new File(sourceDir);

  public void copyRecurse(File source) throws IOException {
    if (source.isDirectory()) {
      File[] children = source.listFiles(filter);
      for (int i = 0; i < children.length; i++) {
    } else {

  public void copyIt(File f) throws IOException {
    System.out.println("Copying " + f.getName() + " to " + targetDir);
    FileCopy.copy(f.getPath(), targetDir);

  class XmlOnly implements FileFilter {

     *Description of the Method
     * @param  f  File or directory to test (file has to be xml)
     * @return    Allowed or not?
    public boolean accept(File f) {
      return f.isDirectory() || f.getName().indexOf(".xml") > -1;



Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mick BarryJava DeveloperCommented:
Unless you have network access to the server directories, then you will need to something running on the server to accept your files such as an ftp server.
Better than

>>return f.isDirectory() || f.getName().indexOf(".xml") > -1;


return f.isDirectory() || f.getName().endsWith(".xml");
alagappanKAuthor Commented:
Hello Object,

I am trying to automate this process using Java, so that I can have the JSP which accept the input source and the destination (maybe I can provide the dropdown list of source and the destination and the user can choose what they want, once the click the submit button, I call this java code to do the mass move of xml and html code.

Hello CEHJ,

I think this code will work for the directory structure I mentioned for the xml. I will have some HTML and JavaScript file to move also. Would you please tell me what I need to do to copy this HTML and JavaScript. HTML and JS file will be in a different directory structure.

I truly appreciate your help,

Thank you,

Kennedy Alagappan
If you're doing this with JSP, you need to adapt the FileCopy class so that you're writing to a URLConnection opened on the JSP rather than a file.

As far as copying html/javascript files is concerned, all you need to do is to change the file filter.
alagappanKAuthor Commented:
Hello CEHJ

can you eloborate little bit on "adapt the FileCopy class". I am not quiet understanding there.

What if I do it from the command prompt of my desktop, do I still need to do any changes. I can make a Batch file in my desktop. People can just run the batch file instead of using JSP file.

your advice is more helpful here.

Before that, can *you* elaborate on

>>People can just run the batch file instead of using JSP file.

? How will that work?
alagappanKAuthor Commented:
I think I stick with the batch file. I haven't tested the code you provided here. I will test it and I will ask you if I have any question. Until then I left this thread open. Is that okay for you CEHJ

Would you please tell me, I can copy the whole xml and html and javascript in a single command or in a multiple command in the Batch file to copy to the server right ??

would you give a sample command please
thank you,
Question - do you want to use this on the same LAN as the server?
alagappanKAuthor Commented:
Yes. I think so. My Data Server is in different building. I need to move the file from my desktop to that Data Server. Yes, it is the LAN Connection.
The you can use the UNC notation as I mentioned and it should be fine.

For the other types of file, you could add a third parameter to main that constructs a different filter. e.g.

FileFilter filter = Class.forName(args[2]).newInstance();

so you could pass:

<x> <y> XmlFilter


<x> <y> HtmlAndJsFilter

FileFilter filter = (FileFilter)Class.forName(args[2]).newInstance();
alagappanKAuthor Commented:
Are you saying, just include this line in the Main method and pass the third argument ??? that should be enough ?

FileFilter filter = (FileFilter)Class.forName(args[2]).newInstance();

thank you

Yes, but you'll have to also

a. make a new class for each filter type
b. set it in the algorithm instead of the one in there now
Mick BarryJava DeveloperCommented:
Be easier to just supply a RE for the filenames you want to match.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.