Java:从FTP服务器访问文件 [英] Java: Accessing a File from an FTP Server

查看:441
本文介绍了Java:从FTP服务器访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

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



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

基本上我想要做的是获取列表



这是我到目前为止:

  URL url = null; 
文件夹= null;
尝试{
url = new URL(ftp:// username:password@www.superland.example/server);
folder = new File(url.toURI());
} catch(Exception e){
e.printStackTrace();
}
data = Arrays.asList(file.listFiles(new FileFilter(){
public boolean accept(File file){
return file.isDirectory();
}
}));

但是我得到错误URI scheme is not'file'。



我明白这是因为我的网址以ftp://开头,而不是file:

但我无法似乎找出了我应该做的事情!



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

解决方案

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

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

考虑替代 FTPClient 来自 Apache Commons Net ,它支持许多协议。以下是 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: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();
    }
}));

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?

解决方案

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

URL url = new URL ("ftp://username:password@www.superland.example/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.

这篇关于Java:从FTP服务器访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆