Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 409
  • Last Modified:

Java Code to Move file from Desktop to Application Server Directory

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
alagappanK
Asked:
alagappanK
  • 13
  • 7
  • 2
1 Solution
 
CEHJCommented:
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
 
CEHJCommented:
For the target directory, you can UNC notation

\\\\machine_name\\share_name\\file_name

The source directory will be

System.getProperty("user.home")

0
 
CEHJCommented:
Sorry

>>
The source directory will be

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

should have been

System.getProperty("user.home") + "\\Desktop";
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

regards,
alagappanK
0
 
CEHJCommented:
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
 
alagappanKAuthor Commented:
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
 
CEHJCommented:
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
 
objectsCommented:
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
 
CEHJCommented:
Better than

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

is

return f.isDirectory() || f.getName().endsWith(".xml");
0
 
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,
regards,

Kennedy Alagappan
0
 
CEHJCommented:
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
 
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.

regards,
alagappanK
0
 
CEHJCommented:
Before that, can *you* elaborate on

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

? How will that work?
0
 
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,
alagappanK
0
 
CEHJCommented:
Question - do you want to use this on the same LAN as the server?
0
 
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.
0
 
CEHJCommented:
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
 
CEHJCommented:
Sorry

FileFilter filter = (FileFilter)Class.forName(args[2]).newInstance();
0
 
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


0
 
CEHJCommented:
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
 
objectsCommented:
Be easier to just supply a RE for the filenames you want to match.
0
 
CEHJCommented:
8-)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 13
  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now