How do I do an FTP delete with Java URLConnection?
I have a simple put and get working, but can't seem to find how to do a delete? For reference, the put code is:
BufferedInputStream inStream = nul开发者_JAVA技巧l;
FileOutputStream outStream = null;
try {
final String ftpConnectInfo = "ftp://"+user+":"+pass+"@"+destHost+"/"+destFilename+";type=i";
LOGGER.info("Connection String: {}", ftpConnectInfo);
URL url = new URL(ftpConnectInfo);
URLConnection con = url.openConnection();
inStream = new BufferedInputStream(con.getInputStream());
outStream = new FileOutputStream(origFilename);
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = inStream.read(bytesIn)) >= 0) {
outStream.write(bytesIn, 0, i);
}
}
Is there some way to modify the URL to do a delete?
Based on this discussion on JavaRanch, I'm not sure you can do it by just modifying the URL. Is there any particular reason why you're not just using a library class like Apache commons FTPClient?
I would take a look at commons-net or commons-vfs for Java FTP, what you are doing here is opening an input stream on a file and reading it, while you want to send a command and get an acknowledgment.
I think the URLConnection is just supposed to allow you to read data.
It implements some commands of the FTP protocol to allow you to fetch files. But i don't think there is any way to sneakily encode a DELETE command in a URL to allow you to do what you want.
As other have said: you have to use a full featured FTP client.
精彩评论