Apart from using Apache Commons Net library, there’s another way to list files and directories on a FTP server: Using FTP URL syntax as follows:

ftp://user:password@host:port/path

Where the path must ends with ;type=d (d is for directory file listing). For example, if you want to list content of a directory /projects/java on the server www.myserver.com using user tomand password secret, build the following URL:

ftp://tom:secret@www.myserver.com/projects/java;type=d

Note that the port parameter can be omitted if using default FTP port (21). Normally, we can paste that URL into a web browser’s address bar and the browser will show content of the directory nicely. In Java, we can use the following simple program:

package net.codejava.ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FtpUrlListing {

	public static void main(String[] args) {
		String ftpUrl = "ftp://%s:%s@%s/%s;type=d";
		String host = "www.myserver.com";
		String user = "tom";
		String pass = "secret";
		String dirPath = "/projects/java";

		ftpUrl = String.format(ftpUrl, user, pass, host, dirPath);
		System.out.println("URL: " + ftpUrl);

		try {
			URL url = new URL(ftpUrl);
			URLConnection conn = url.openConnection();
			InputStream inputStream = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

			String line = null;
			System.out.println("--- START ---");
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("--- END ---");

			inputStream.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

The key point in this program is reading the input stream of the opened URLConnection, by using a BufferedReader to read the stream line by line. The program would produce the following output:

--- START ---

.

..

HibernateAnnotationTutorial

SpringMVCFileUpload

Struts2EmailApp

Readme.txt

--- END ---

Note that the line which has only one dot indicates current directory and the one with two dots indicates parent directory.

Though simple to use, this method lets us know only names of the files and directories. If we want more information such as size and modification time, we have to use a third-party library like Apache Commons Net library.

 

Related Java FTP Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (FtpUrlListing.java)FtpUrlListing.java[ ]1 kB

Add comment