Saturday, January 21, 2006

Basic Java FTP

Looking for ways to ftp (put) files in Java, I found the hidden classes which come with the jdk anyway.
Thanks to a javaworld article that can be found here.
It's unsafe to use, and not really documented, but does the job for the most basic ftp tasks - and its part of current Sun JDK distributions. Might obviously vanish in the future. But its still there in 1.5.

Basically you need:

and then you can magically

String ftpserver ="";
String ftpuser = ...;
String ftppasswd = ...;

FtpClientclient = new FtpClient();
client.login(ftpuser, ftppasswd);

// client.binary();

OutputStream out = client.put(destfilename);

actually it is a, but thats a hidden implementation anyway. So at this point you have an OutputStream and do whatever you want to do with it.

// etc

to close it, just do a

out.close(); // for the file
client.closeServer(); // for the connection

Some people report problems with it, but it works fine for me.

The beauty of it is, that you work with a regular OutputStream (which you can of coure pass to an OutputStreamWriter to get a Writer), so all the code you have that works on any of those output classes just runs with it... in my case the rome library from to create RSS/Atom feeds.


Robert "kebernet" Cooper said...

The Jakarta Commons FTP client is really quite nice.

Roman said...

great pointer, don't know why I haven't found that earlier; thanks