Вопрос

I am developping a DeployIt-like application, where a file (for example a JAR) has to be copied from one server and pasted to another. The most important aspect of this is that it has to be done atomically, without intermediate environments (like localhost).

I have managed to copy a file from one server to the local machine and then to the target server, but this operation is time-consuming and we cannot afford that.

URL url = new URL(path);
File result = new File("C:\\" + fileName);
FileUtils.copyURLToFile(url, result); // copy to local machine
FileObject localFile = manager.resolveFile(f.getAbsolutePath());
FileObject remoteFile = manager.resolveFile(
            createConnectionString(hostname, username, password, remoteFilePath, f.getName()), createDefaultOptions());

remoteFile.copyFrom(localFile, Selectors.SELECT_SELF); // copy to target server

How can I do that in one step?

Это было полезно?

Решение

Provided you can obtain an InputStream from the source socket and an OutputStream from the destination socket, you can use a method which will avoid copying into a file, such as:

public static void copyStream(final InputStream in, final OutputStream out)
    throws IOException
{
    final byte[] buf = new byte[32768]; // or more, or less; size appropriately
    int nrBytes;

    while ((nrBytes = in.read(buf)) != -1)
        out.write(buf, 0, nrBytes);

    out.flush();
}

However, before going this way and avoid a temporary file inbetween, consider what would happen if you had a short read or short write; how do the endpoints behave in this case?

Also, note that this method does not close either stream; you'll have to do it yourself.

Другие советы

You can use UNC path to map drive(if you have access). It will be fast because it uses CIFS protocol which is fast. The syntax will be something like.

new File("//SERVER/some/path").toURI().toString() -> "file:////SERVER/some/path
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top