user3008362
user3008362

Reputation: 51

Java sshj libary, create file onto sftp linux server without an actual file

The software I am working with has net.schmizz.sshj jars as part of it. I am trying to use the same to write a csv bytestring into a csv file on an SFTP server

I have searched quite a bit but not able to find a method in this library which can take an InputStream, the only options seem to take an existing file path or a File object.

I need to be able to do this without actually creating a file on the local side as the software is SaaS delivered and we dont have permission to create an actual file on the hosting server. The file should only get created on the SFTP server

Is there any option around this? Or the only option is to go with some other library?

Upvotes: 0

Views: 804

Answers (1)

Jokkeri
Jokkeri

Reputation: 1055

I think here is something you could try (using java SSHJ-lib):

    SSHClient ssh;
    SFTPClient client;
    
    ssh = new SSHClient();
    
    ssh.connect("myhost");
    
    client = ssh.newSFTPClient();
    
    // Overwrites the file in dest
    RemoteFile handle = client.open("/path/to/my/file.txt",
            EnumSet.of(OpenMode.WRITE, OpenMode.READ,
                    OpenMode.CREAT, OpenMode.TRUNC));
    
    
    InputStream input = null;
    byte[] bytes = new byte[32768];
    int len = 0;
    long total = 0;
    
    input = getMyInputStreamFromSomeWhereOtherThanFile();
    
    while ((len = input.read(bytes)) > 0) {
        handle.write(total, bytes, 0, len);
        total += len;
    }
    
    System.out.println("Total of " + total + " bytes written");

Of course the code needs still lots of modifications like handling and closing the streams, setting up connection parameters etc. but this gets you the idea on how you can write using stream.

Upvotes: 0

Related Questions