Java:从FTP服务器访问文件

时间:2013-01-22 20:07:24

标签: java file url ftp

所以我的FTP服务器里面有很多文件夹和文件。

我的程序需要访问此服务器,读取所有文件并显示其数据。

出于开发目的,我一直在使用硬盘上的文件,就在“src”文件夹中。

但是现在服务器已启动并运行,我需要将软件连接到它。

基本上我想要做的是获取服务器上特定文件夹中的文件列表。

这是我到目前为止所做的:

URL url = null;
File folder = null;
try {
    url = new URL ("ftp://username:password@www.superland.example/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();
    }
}));

但我收到错误“URI scheme is not'file'。”

我理解这是因为我的网址以“ftp://”开头而不是“file:”

然而,我似乎无法弄清楚我应该怎么做呢!

也许有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:11)

File个对象无法处理FTP连接,您需要使用URLConnection

URL url = new URL ("ftp://username:password@www.superland.example/server");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream();
...

考虑作为Apache Commons Net的替代FTPClient,它支持许多协议。这是一个FTP list files example

答案 1 :(得分:3)

如果你将URI与文件一起使用,你可以使用你的代码但是,当你想使用ftp时,你需要这种代码;代码列出了ftp服务器下文件的名称

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL url = new URL("ftp://username:password@www.superland.example/server");
        URLConnection con = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

已编辑 Demo Code Belongs to Codejava

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();
        }
    }
}