[英]Java: Accessing a File from an FTP Server
所以我有這個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:”開頭
但是我似乎無法弄清楚我應該怎么做呢!
也許有更好的方法來解決這個問題?
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列表文件示例 。
如果你將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();
}
}
EDITED 演示代碼屬於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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.