Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Accessing a File from an FTP Server

Tags:

java

file

url

ftp

So I have this FTP server with a bunch of folders and files inside.

My program needs to access this server, read all of the files, and display their data.

For development purposes I've been working with the files on my hard drive, right in the "src" folder.

But now that the server is up and running, I need to connect the software to it.

Basically what I want to do is get a list of the Files in a particular folder on the server.

This is what I have so far:

URL url = null;
File folder = null;
try {
    url = new URL ("ftp://username:[email protected]/server");
    folder = new File (url.toURI());
} catch (Exception e) {
    e.printStackTrace();
}
data = Arrays.asList(folder.listFiles(new FileFilter () {
    public boolean accept(File file) {
        return file.isDirectory();
    }
}));

But I get the error "URI scheme is not 'file'."

I understand this is because my URL starts with "ftp://" and not "file:"

However I can't seem to figure out what I'm supposed to do about it!

Maybe there's a better way to go about this?

like image 638
Rich Young Avatar asked Jan 22 '13 20:01

Rich Young


1 Answers

File objects cannot handle an FTP connection, you need to use a URLConnection:

URL url = new URL ("ftp://username:[email protected]/server");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream();
...

Consider as an alternative FTPClient from Apache Commons Net which has support for many protocols. Here is an FTP list files example.

like image 62
Reimeus Avatar answered Sep 25 '22 23:09

Reimeus