Saturday, January 21, 2006

Basic Java FTP

Looking for ways to ftp (put) files in Java, I found the hidden
sun.net.ftp 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:
import sun.net.ftp.*;

and then you can magically

String ftpserver ="ftp.foo.bar";
String ftpuser = ...;
String ftppasswd = ...;

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

// client.binary();
// client.cd("/wherever");

OutputStream out = client.put(destfilename);

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

out.write(...);
// 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 java.net to create RSS/Atom feeds.

2 comments:

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