Solved

Java Code to Move file from Desktop to Application Server Directory

Posted on 2003-12-09
22
382 Views
Last Modified: 2010-03-31
Hello,

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.

regards,
alagappanK
0
Comment
Question by:alagappanK
  • 13
  • 7
  • 2
22 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9904553
You can use this class to shift them:



// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// 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 http://www.davidflanagan.com/javaexamples

import java.io.*;

/**
 * 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): ");
      System.out.flush();
      // Get the user's response.
      BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
      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 = from.read(buffer)) != -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);
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9904563
For the target directory, you can UNC notation

\\\\machine_name\\share_name\\file_name

The source directory will be

System.getProperty("user.home")

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9904668
Sorry

>>
The source directory will be

System.getProperty("user.home")
>>

should have been

System.getProperty("user.home") + "\\Desktop";
0
 

Author Comment

by:alagappanK
ID: 9904787
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

regards,
alagappanK
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9904833
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.

"\\\\machine_name\\share_name\\file_name"

gives the format. Of course, you willhave to *have* a share (share_name) on the target machine over the network
0
 

Author Comment

by:alagappanK
ID: 9904996
Here is my source directory structure looks like

C:\myProject
            Group10
                    whxdata (it contains all xml files)
            Group20
                    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,
alagappanK
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 9905522
You can use this to call it:

import java.io.*;

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 {
      fc.copyAll();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

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

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

  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;
    }

  }

}
0
 
LVL 92

Expert Comment

by:objects
ID: 9907483
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9911937
Better than

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

is

return f.isDirectory() || f.getName().endsWith(".xml");
0
 

Author Comment

by:alagappanK
ID: 9912406
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,
regards,

Kennedy Alagappan
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9912446
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.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:alagappanK
ID: 9912597
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.

regards,
alagappanK
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9912622
Before that, can *you* elaborate on

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

? How will that work?
0
 

Author Comment

by:alagappanK
ID: 9912740
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,
alagappanK
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9912793
Question - do you want to use this on the same LAN as the server?
0
 

Author Comment

by:alagappanK
ID: 9914757
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9914849
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

or

<x> <y> HtmlAndJsFilter
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9914858
Sorry

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

Author Comment

by:alagappanK
ID: 9915879
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


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9915935
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
0
 
LVL 92

Expert Comment

by:objects
ID: 9916199
Be easier to just supply a RE for the filenames you want to match.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10640810
8-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
hash value 2 39
Performance issue while iterating with streams 5 39
Systems talking to each other 5 110
JAVA part two 5 41
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now