Java connect to FTP server and download files with java default libraries

I need to connect to an FTP server and browse all files without using any libraries like apache.commons because I don’t have the option to get these libraries at the moment.

I tried using a simple URL connection:

URL url = new URL("username:[email protected]/folder/");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;

while ( (line = reader.readLine()) != null ) {
    System.out.println(line);
}

reader.close();

When I don’t include the /folder/ it works, but it prints me many things that I can’t even see in the home location of the FTP server, I don’t know if it gives me the files or other data.

But when I do include /folder/ i get error CWD /folder/:550 failed to change directory

and I cannot change the directoy’s permissions, its read-only and thats what I need.

What is wrong with it? Is it possible to do with just java’s default libraries?

Answer

First, you need to use an FTP URL:

URL url = new URL("ftp:username:[email protected]/folder/");

assuming username and password are substituted with their correct values.

Second, if you have FTP access to folder it will deliver you a directory listing in some format. If you don’t, you need to study the exception message you get. If you omit /folder it will give you a listing of whatever the FTP server’s default root directory is for that username. The code 550 means either an access problem or that the directory doesn’t exist.

Leave a Reply

Your email address will not be published. Required fields are marked *