简体   繁体   中英

Copy Files Between Windows Servers with Java?

I'm looking for code, or a library, which I can use to copy files between Windows servers using Java. Picture a primary server that runs a background thread, so that whenever a transaction is completed, it backs up the database files to the backup server. (This is required protocol, so no need to discuss the pros/cons of this action). In other words, transaction completes, Java code gets executed which copies one directory to the back-up server.

The way the Windows machines are set up, the primary server has the back-up server's C: drive mapped as it's own Z: drive. Both machines running Windows 2003 or 2008 Server. Java 1.6.

Found the correct answer on another forum and from messing around a little with the settings. The problem with copying files from one machine to another in Windows (using either a .bat file or using straight-up Java code) is the user permissions. On the primary server, you MUST set the Tomcat process to run as the administrator, using that administrator's username and password. (Right-click on the Tomcat service, select "Log On" tab, enter administrator's username/password). The default user that Tomcat runs on (local user), isn't sufficient to copy files between networked drives on Windows. When I set that correctly, both the .bat file solution I had tried previous to this post, and a straight-Java solution suggested here worked just fine.

Hope that helps someone else, and thanks for the suggestions.

Obtain the files by File#listFiles() on a directory from one disk, iterate over each of them, create a new File on the other disk, read from a FileInputStream from the file from one disk and write it to a FileOutputStream on the file on the other disk.

In a nut:

for (File file : new File("C:/path/to/files").listFiles()) {
    if (!file.isDirectory()) {
        File destination = new File("Z:/path/to/files", file.getName());
        // Do the usual read InputStream, write OutputStream job here.
    }
}

See also:


By the way, if you were using Java 7, you would have used Path#copyTo() for this.

Paths.get("C:/path/to/files").copyTo(Paths.get("Z:/path/to/files"));

I would really recommend using Apache Commons IO for this.

The FileUtils class provides methods to iterate over directories and copy files from one directory to another. You don't have to worry about reading and writing files yourself because it's all done by the library for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM