javasshj

Streaming remote files into file objects


If anyone knows a quick way how to get a remote file directly streaming into a file object, so it isn't necessary to store the file temporary on a computer it would be greatly appreciated! Until now I copy the file from a remote ios-device as follows (using net.schmizz.sshj):

SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(fingerprint);
ssh.connect(ip);

try {
    ssh.authPassword("username", "userpassword".toCharArray());
    ssh.newSCPFileTransfer().download(fileRemote, new FileSystemFile(fileLocal));
} catch (IOException ioe) {
    ioe.printStackTrace();
} finally {
    ssh.disconnect();
}

If there's anyone who's interested in the code of the solution:

As Nutlike mentioned in his answer it's better to use InMemoryDestFile. So create the following class:

class MyInMemoryDestFile extends InMemoryDestFile {
    public ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    @Override
    public ByteArrayOutputStream getOutputStream() throws IOException {
        return this.outputStream;
    }
}

... in your method where you perform the download operation create an instance of your new class:

MyInMemoryDestFile a = new StreamingInMemoryDestFile();

and access the outputstream:

ssh.newSCPFileTransfer().download(remoteFile, a);
a.getOutputStream().toByteArray();

best regards


Solution

  • Would it not be sufficient to use InMemoryDestFile instead of FileSystemFile?

    Edit: … and then use getOutputStream() to access the 'file' …