8

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();

2 Answers 2

10

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".

2
  • even though it sounds more like exploiting than standard procedure, I did find this a really useful solution! I didn't want to use any external libs as well, nor sun.net.ftp directly. And apache commons FTPClient does not support proxies (besides system properties) and it is an external lib. Thanks for the solution! Jun 28, 2011 at 15:15
  • Actually, this is standart way. It follows RFC 1738 (datatracker.ietf.org/doc/rfc1738) which is not yet obsoleted in part of FTP URL scheme May 4, 2013 at 13:18
1

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

1
  • 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
    Jul 22, 2009 at 3:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.