Question

I'm a bit confused. I got this block of code :

public void serializeStock(){

    FTPClient client = new FTPClient();

    try{
        client.connect("ftp.**.***");
        client.login("***", "*****");

        FileInputStream fin = new FileInputStream(someVariableContainingObject); // <-- The object ( StockVault stocks = new StockVault();
        ObjectInputStream oos = new ObjectInputStream(fin);
        client.storeFile("theObject", oos);
        System.out.println("Wrote Stocks data to file");

        client.logout();
        client.disconnect();
    }catch(Exception ex){
        ex.printStackTrace();
    }
}

I open a connection to my remote FTP server, I now want to write a object named "stocks" to the server. I know I can save the object file first, and then upload it. But is it possible to store the object in a "file" variable or something, and feed it directly to the FileInputStream? This way I wont have to save the object to an actual system file, and then upload it. But make some kind of variable to hold the file, and then upload the "file-variable" to the ftp-server.

Was it helpful?

Solution

It is possible to stream directly to the FTP server, but FileInputStream is not the right class to do so -- it always reads from a local file.

The simplest way to do this in your case may be to use

client.storeFileStream(remoteName)

This method returns an output stream you can write to (instead of sucking up all the data from a given input stream), which seems to be a more natural fit for your case.

Example:

OutputStream os = client.storeFileStream("theObject");
ObjectOutputStream oos = new ObjectOutputStream(os);

// write your object to oos here,
// then close everything.

An alternative that uses the same client method as in your example but no file would be to first write the object to a ByteArrayOutputStream, then create a ByteArrayInputStream from getBytes(), and hand that over to the ftp client.

BTW: The Object stream in your code can be omitted -- you can use the file stream directly:

FileInputStream fin = new FileInputStream(someVariableContainingObject); 
client.storeFile("theObject", fin);
// ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top