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.

1 comment:

for IT the said...

Java Standard Edition Java Enterprise Edition Certification Training Course ware Java Training in Chennai . Java Development Kit JDK J2EE Training in Chennai Java Runtime Environment JRE Java Course in Chennai on Linux Java Interview Questions . IT Technical Articles Java SE Java EE Java Online Course Oracle Learning Tutorials. Java EE Training Java is a great cross-platform programming language. Java EE & Java SE Java Training Institutes in Chennai on Linux Training Course Materials. java j2ee training institutes in chennai