I am writing an application that involves multiple clients. One client uploads a file using FTP to a server, and then another client downloads the file and deletes it. I am using the FTP server kind of as a middleman to exchange information because I do not want the user to have to port forward. I have figured out how to upload a file, but I cannot figure out how to delete the file. The command for deleting a file using FTP is:
DELE <filename>
I have tried doing so, but with no success. Here is the code that I have tried:
public static void deleteFile(String name) throws IOException
{
URL url = new URL("ftp://a1111111:password@mywebsite.com/public_html/misc/screenshots/picture.png;type=i");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(url.openConnection().getOutputStream()));
writer.write("DELE picture.png");
writer.flush();
}
I have a feeling that the < filename > that I provided may be wrong because I did not include the directory names in the path. However, since I explicitly told the path that of the file in the URL, I am not quite sure what I am supposed to enter for the < filename >.
I have read other questions on this web site about problems very similar to this and all of the responses tell to use a library. The thing is, most of those libraries are written in pure Java so the developers of that library had to figure out a way to do what I am trying to do without a library. I want to do that as well. I do not like attaching extra files besides my own to the things that I make. So please, do not tell me to use a library – it’s not what I’m looking for.
If you need any clarification, please ask!
EDIT: If I use this code to receive a response:
byte[] response = new byte[conn.getInputStream().available()];
conn.getInputStream().read(response);
System.out.println("Response: " + new String(response));
My command just gets echoed back:
Response: DELE test1.png
I think you need to do the retrieve and delete in two separate operations; some random documentation I found for
FtpURLConnectionsays, in part:I did not see any methods in the documentation that would allow deleting a file.
You may wish to use the
URLmechanism to retrieve the file, but I would drop down to using raw sockets to delete the file. Create a new connection to the FTP command port, log in, and issue theDELEcommand manually. If this is the only step you’re taking, you might be able to get away with doing relatively poor error handling and maybe only tworead()requests and simply show the output transcript to the user once you’re done.It’s a bit dirty, but I completely understand not wanting to carry around a megabyte of additional source to achieve the moral equivalent of
echo -e "user foo\npass password\ndele /path/to/file\nlogout" | nc ftp.remote.example.com 21.