Solved

copy files in a folder

Posted on 2004-09-15
10
240 Views
Last Modified: 2010-03-31
Hello, How can I copy all of the files in a folder to another folder? I want the files in the original folder to remain.
Thank you.
0
Comment
Question by:CtrlCtrlV
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 12067176
You will have to iterate each one and copy it. You can use the following class by a known Java author:

/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */
package com.davidflanagan.examples.io;
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> <destination>");
        else {
            // Call copy() to do the copy; display any error messages
            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("no such source file: " + from_name);
        if (!from_file.isFile())
            abort("can't copy directory: " + from_name);
        if (!from_file.canRead())
            abort("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("destination file is unwriteable: " + to_name);
            // Ask whether to overwrite it
            System.out.print("Overwrite existing file " + to_file.getName() +
                       "? (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("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();  // The destination directory
            if (parent == null)     // If none, use the current directory
            parent = System.getProperty("user.dir");
            File dir = new File(parent);          // Convert it to a file.
            if (!dir.exists())
                abort("destination directory doesn't exist: "+parent);
            if (dir.isFile())
                abort("destination is not a directory: " + parent);
            if (!dir.canWrite())
                abort("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];         // 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 until EOF
                to.write(buffer, 0, bytes_read);            // write
        }
        // 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("FileCopy: " + msg);
    }
}
0
 

Author Comment

by:CtrlCtrlV
ID: 12067388

But how can I go through all of the files until they are copied?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12067480
Get the files in the directory you want:

File currentDir = new File(".");
String[] files = currentDir.list();

// now use the above class
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:CtrlCtrlV
ID: 12067599
This is what im using,

import java.io.*;

File currentDir = new File("c:\\Lynmore\\previousorders");
String[] files = currentDir.list();
FileInputStream from = null;  // Stream to read from source
FileOutputStream to = null;   // Stream to write to destination
from = new FileInputStream(files);  // Create input stream
to = new FileOutputStream("\\LynmoreBackup\\previousorders\\");     // Create output stream
byte[] buffer = new byte[4096];         // To hold file contents
int bytes_read;                         // How many bytes in buffer
while((bytes_read = from.read(buffer)) != -1) // Read until EOF
to.write(buffer, 0, bytes_read);            // write

But im getting this error:
cannot resolve symbol
symbol  : constructor FileInputStream  (java.lang.String[])
location: class java.io.FileInputStream
    from = new FileInputStream(files);  // Create input stream
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12067628
>>This is what im using,

Why? The code above already does a massive percentage of what you've just written. You just need to call FileCopy.copy(x,y) on each file
0
 
LVL 2

Expert Comment

by:SergeiKo
ID: 12069301
Hello.

You may also look at
http://www.javaalmanac.com/egs/java.io/CopyDir.html?l=new

for example on copying directory.

Regards.
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
ID: 12071381
try something like this:

File currentDir = new File("c:\\Lynmore\\previousorders");
String[] files = currentDir.list();
byte[] buffer = new byte[4096];         // To hold file contents
int bytes_read;                         // How many bytes in buffer
for (int i=0; i<files.length; i++)
{
   if (!files[i].isDirectory())
   {
      FileInputStream from = null;  // Stream to read from source
      FileOutputStream to = null;   // Stream to write to destination
      from = new FileInputStream(files[i]);  // Create input stream
      to = new FileOutputStream(new File("\\LynmoreBackup\\previousorders\\", files[i].getName()));     // Create output stream
      while((bytes_read = from.read(buffer)) != -1) // Read until EOF
         to.write(buffer, 0, bytes_read);            // write
      from.close();
      to.close();
   }
}

0
 

Author Comment

by:CtrlCtrlV
ID: 12198699
Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12198720
:-)
0
 
LVL 92

Expert Comment

by:objects
ID: 12204607
glad i could help (:
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ejb on wildfly 5 59
difference between sorce folder and folder in eclipise 3 60
web project error add remove 1 75
convert Absolute path to relative path of FTP location 7 46
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

733 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