tags:

views:

184

answers:

2

I'm using the Java URL and URLConnection classes to upload an file to a server using FTP. I don't need to do anything other than simply upload the file, so I'd like to avoid any external libraries and I'm wary of using the non-supported sun.net.ftp class.

Is there any way to use absolute paths in the FTP connection string? I'd like to put my files in something like "/ftptransfers/..." but the FTP path is relative to the user home directory.

Sample upload code:

URL url = new URL("ftp://username:password@host/file.txt");
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
OutputStream out = uc.getOutputStream() ;
out.write("THIS DATA WILL BE WRITTEN TO FILE".getBytes());
out.close();
+1  A: 

I think that your best bet is to use the apache commons FTP component, and do a 'cd' after you make the connection.

you can always write a wrapper so that the URL can be specified in the format above if you so wish.

-ace

phatmanace
as much as the OP doesn't want to use an external library, I think this is a case where it's called for (unless he wants to implement the cd command himself, which I guess he could do)
Kevin Day
A: 

I did actually find out there is a semi-standard way to do it that worked for me.

Short answer: replace the leading slash with "%2F"

Long answer: per the "A FTP URL Format" document:

For example, the URL "ftp://[email protected]/%2Fetc/motd" is interpreted by FTP-ing to "host.dom", logging in as "myname" (prompting for a password if it is asked for), and then executing "CWD /etc" and then "RETR motd".

This has a different meaning from "ftp://[email protected]/etc/motd" which would "CWD etc" and then "RETR motd"; the initial "CWD" might be executed relative to the default directory for "myname".

On the other hand, "ftp://[email protected]//etc/motd", would "CWD " with a null argument, then "CWD etc", and then "RETR motd".

Brian