Monday, January 12, 2009

FTP in Java

This one is a reminder as well; the example is not complete but I'm sure that it will be enough to get to the point.

FTP is not directly supported in Java, rather it is disguised behind a URLConnection. Once you've opened the connection you just access the appropriate stream and normally use it:

URL url = new URL("ftp://username:password@your.host/complete/path/to/remote/file");
URLConnection connection = url.openConnection();

To "get" a file you use the input stream:

InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);

then you create a writer...

FileWriter writer = new FileWriter(new File("complete/path/to/local/file"));

and flush what you read:

int tmp;
while ((tmp = reader.read()) != -1) {
writer.write(tmp);
}

aren't we forgetting anything? oh yes, clean up the room:

reader.close();
writer.close();

The dual "put" operation requires an output stream:

OutputStream os = connection.getOutputStream();

and the core of the transfer loop would simply be

os.write(tmp);

Ok, the read-and-flush code is quite ugly, one would problably wrap the reader in a BufferedReader, append and flush instead of directly writing and stuff, but for version 0.1 it will suffice.

For most advanced needs it is always possible to use the Commons Net.

No comments: