Well, I've been learning Java and I managed to create an FTP client that uploads and downloads files from a server. Oddly, the thing I can't figure out is how to do an FTP delete. Can anyone help me on that? I don't want to use an API or someone else's class. (How would I learn from that? ;)

I've tried looking through some existing API's for hints, but their too complicated for me to figure out. You have to go from function to function in tons of files and I still don't get it.

Any help or suggestions would be great! Thanks everyone.

Well, I've been learning Java and I managed to create an FTP client that uploads and downloads files from a server. Oddly, the thing I can't figure out is how to do an FTP delete. Can anyone help me on that? I don't want to use an API or someone else's class. (How would I learn from that? ;)

I've tried looking through some existing API's for hints, but their too complicated for me to figure out. You have to go from function to function in tons of files and I still don't get it.

Any help or suggestions would be great! Thanks everyone.

might this help:

package org.kodejava.example.commons.net;

import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;

public class FtpDeleteDemo {

    public static void main(String[] args) {
        FTPClient client = new FTPClient();
        try {
            client.connect("ftp.domain.com");
            client.login("admin", "secret");
// Delete file on the FTP server. When the FTP delete complete 
// it returns true.
            String filename = "/testing/data.txt";
            boolean deleted = client.deleteFile(filename);
            if (deleted) {
                System.out.println("File deleted...");
            }
            client.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Thanks for the quick reply. That code uses the ftpClient API, which I'm trying to avoid. :( Is there an example that doesn't use an API?

Have you read the RFC on how FTP works?
You can use a Socket connection to send the FTP server commands made of Strings.
You need to know the protocol for it to work.

How would I go about that? I've never understood sockets. I mean, I understand the concept, but I've never successfully used them. I guess what I am asking is, where is a good place to go to understand sockets and how they relate to my current dilemma?

Thanks for the link. Thus far in my code I've used things like:

//conn is a URLConnection. A socket of sorts, I suppose...

	OutputStream os = conn.getOutputStream();
  	BufferedOutputStream bos = new BufferedOutputStream(os);

  	byte[] buffer = new byte[1024];
  	int r;

  	while((r = bis.read(buffer)) > 0){
  		//write the file
  	}

which I've never really thought of as sockets.

That could work. Try it and see how it goes.

Haha. I feel foolish now. That tutorial is essentially what I am doing. I guess when I think of Sockets I think of the C++ methods that are infinitely more complex.

At any rate, how can I use that to delete a file? I understand how to transfer a file with it, but somewhere in my disconnected brain I can't figure out how use it to remove a file.

EDIT: cross post. The above does work for uploading. As I said, I can upload and download, I just can't delete files.

With FTP you send a request to the server. The server does what you ask.
You need to read the doc on the protocol. One place is the RFC doc for FTP.

So, I looked through http://www.w3.org/Protocols/rfc959/8_PortNumber.html and some other specs on W3C, but I still don't understand. Forgive my slow-ness. I know the command that I need to send to the server is

DELE <SP> <pathname> <CRLF>

but I don't know how to send it with Java. Do you?

Connect to the server and send the command as a String.

I don't know if this will be helpful or confusing. I wrote an FTP Server a few years ago.
Here is its console log from when I connect to it with a FTP tool: WS_FTP95.

FTPrun(): connected accepted Socket[addr=/127.0.0.1,port=4145,localport=21]
ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=21]
MyIP4PASV: 127,0,0,1,
writeString: writing >220 Norms FTP server ready.
< (end of writing) <<<
FTPreq: >USER Norm<
writeString: writing >331 Password required.
< (end of writing) <<<
FTP req: PASS asdf
writeString: writing >230 User logged in.
< (end of writing) <<<
FTP request: PWD
writeString: writing >257 "D:/www/" is current directory.
< (end of writing) <<<
FTP request: SYST
writeString: writing >215 NAME Norm's FTP Server
< (end of writing) <<<
FTP request: HELP
writeString: writing >214-The following commands are recognized:
USER
QUIT
ABOR
TYPE
LIST
PWD
MKD
CWD
TYPE
PORT
SYST
HELP
NLST
CDUP
PASV
RETR
STOR
214 Help command successful.
< (end of writing) <<<
FTP request: PORT 127,0,0,1,16,50
dpH RmtAddr: 127.0.0.1:4146
dpH OSocket: Socket[addr=/127.0.0.1,port=4146,localport=20]
writeString: writing >220 PORT Command successful.
< (end of writing) <<<
FTP request: LIST
writeString: writing >150 Opening ASCII mode data connection.
< (end of writing) <<<
dpHdoLIST: >< true
writeString: writing >226 Transfer complete.
< (end of writing) <<<
FTP request: PWD
writeString: writing >257 "D:/www/" is current directory.
< (end of writing) <<<
FTP request: PORT 127,0,0,1,16,51
dpH RmtAddr: 127.0.0.1:4147
dpH OSocket: Socket[addr=/127.0.0.1,port=4147,localport=20]
writeString: writing >220 PORT Command successful.
< (end of writing) <<<
FTP request: LIST
writeString: writing >150 Opening ASCII mode data connection.
< (end of writing) <<<
dpHdoLIST: >< true
writeString: writing >226 Transfer complete.
< (end of writing) <<<
FTP request: QUIT
User: Norm logged off
writeString: writing >221 Goodbye.
< (end of writing) <<<
FTPrun(): waiting on connect at Mon Jan 23 21:07:52 EST 2012 ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=21]

The Strings inside of the > < are what the server received or sent.
The one in red was received from the client.
The one in green was what was sent to the client

Thank you for sticking with me on this. The concept of what needs to be done is relatively clear (ish), but the application is completely absent. I haven't the slightest idea how to send that String command to the FTP server. I know sockets will need to be involved, but I don't understand the specifics. Essentially, this is the conundrum that I've been stuck on for the past week or so.

Suppose I do a URLConnection again to connect to the server, where specifically would the string go and how would I get it there? I imagine that I wouldn't still be using a BufferedOutputStream. And I have my doubts that the URLConnection would even be appropriate-- to which URL would I connect? If it's to the file I want deleted, wouldn't it the write the command to the file rather than execute it? I'm so confused. Any application help would be fantastic.

See my last post. It has part of a dialog between a FTP server and a client.
The client was an FTP tool I got years ago. I suspect it uses sockets.

Sorry, I missed that edit. From what you posted, it looks like I should set up a connections to the top-level domain, or perhaps even the IP Address (though I don't suppose it would really make a difference either way). Now I have to figure out how to send FTP commands. . . .

how to send FTP commands.

Use the output stream you get from a Socket.

Like this?

try{
			URL url = new URL("ftp://"+this.user+":"+this.password+"@"+this.url);
			URLConnection conn = url.openConnection();

			OutputStream os = conn.getOutputStream();
		  	BufferedOutputStream bos = new BufferedOutputStream(os);

		  	String cmd = "DELE "+file+"\n";

		  	bos.write(cmd.getBytes());
		  	
		  	bos.close();
	      
		  	return "\n     File Deleted!";
		}catch(Exception ex){
			return "\n     File Failed to delete!";
		}

I don't think it will work....

EDIT:

java.io.IOException: illegal filename for a PUT
at sun.net.www.protocol.ftp.FtpURLConnection.getOutputStream(Unknown Source)
at ftpClient.ftpdel(ftpClient.java:155)
at console.ftpDel(console.java:676)
at console.localCommand(console.java:436)
at console.proccessCommand(console.java:347)
at console.runCommand(console.java:263)
at console$3.keyTyped(console.java:114)
at java.awt.Component.processKeyEvent(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

How does the short piece of code relate to the stack trace?
For example: Where is line 155

What is the value of the variable: url?

OH MY GOSH!

try{
			Socket socket = new Socket (this.url, 21);
			PrintStream out = null;
			out = new PrintStream (socket.getOutputStream());
			out.println("user "+ this.user + "\n");
			out.println("pass "+ this.password + "\n");
			out.println("DELE "+ file + "\n");
			out.close();
			return "Okay!";
		}catch(Exception e){
			e.printStackTrace();
			return "Fail!";
		}

THAT'S IT! IT WORKS! My FTP Client is FINIHSED!!!

Thanks for your insights, my friend.

Congratulations on getting your code to work.

I wouldn't say it was finished, but at least you have the basics done.

Has anybody used m_Ftp.getOutputStream()

import com.jscape.inet.ftp.Ftp;

m_Ftp = new Ftp(m_strServer, m_strUser, m_strPassword);
m_Ftp.getOutputStream("test",0,false);

Can anyone help me with example for this

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.