Java连接到FTP服务器并使用java默认库

时间:2016-07-05 06:28:48

标签: java ftp

我需要连接到FTP服务器并浏览所有文件而不使用像apache.commons这样的库,因为我现在没有选择获取这些库。

我尝试使用简单的网址连接:

URL url = new URL("username:password@ip/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();

当我没有包含/folder/它的作品时,它会打印出很多我甚至无法在FTP服务器的原始位置看到的东西,我不会知道它是否给我文件或其他数据。

但当我确实包含/folder/时,我收到错误CWD /folder/:550 failed to change directory

我无法更改directoy的权限,只读它的权限,这就是我需要的权限。

它出了什么问题?是否可以只使用java的默认库?

2 个答案:

答案 0 :(得分:2)

首先,您需要使用FTP URL:

URL url = new URL("ftp:username:password@ip/folder/");

假设usernamepassword被替换为正确的值。

其次,如果您有folder的FTP访问权限,它将以某种格式向您提供目录列表。如果你没有,你需要研究你得到的异常消息。如果省略/folder,它将为您提供FTP服务器默认根目录的username列表。代码550表示访问问题或目录不存在。

答案 1 :(得分:-2)

即使您需要搜索内部目录或文件夹,此代码也能完美运行

public class FilesDownload {

public static void main(String[] args) {
        int port = 21;
        String server = "for example remote ip";
        String user = "the username";
        String pass = "the access password";
 
        FTPClient ftpClient = new FTPClient();
 
        try {
            // connect and login to the server
            ftpClient.connect(server, port);
            ftpClient.login(user, pass);
 
            // use local passive mode to pass firewall
            ftpClient.enterLocalPassiveMode();
 
            System.out.println("Connected");
 
            String remoteDirPath = "/your folder";
            String saveDirPath = "your final path to save files";
            listDirectory(ftpClient, remoteDirPath, "", 0); //this function is just to show you what you have inside the folder

            FTPUtil.downloadDirectory(ftpClient, remoteDirPath, "", saveDirPath);
 
            // log out and disconnect from the server
            ftpClient.logout();
            ftpClient.disconnect();
 
            System.out.println("Disconnected");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

 static void listDirectory(FTPClient ftpClient, String parentDir,
            String currentDir, int level) throws IOException {
        String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }
        FTPFile[] subFiles = ftpClient.listFiles(dirToList);
        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".")
                        || currentFileName.equals("..")) {
                    // skip parent directory and directory itself
                    continue;
                }
                for (int i = 0; i < level; i++) {
                    System.out.print("\t");
                }
                if (aFile.isDirectory()) {
                    System.out.println("[" + currentFileName + "]");
                    listDirectory(ftpClient, dirToList, currentFileName, level + 1);
                } else {
                    System.out.println(currentFileName);
                }
            }
        }
    }
}
 

然后你需要创建名为 FTPUtil 的 Auxiliary 类:

public class FTPUtil {
public static void downloadDirectory(FTPClient ftpClient, String parentDir,
        String currentDir, String saveDir) throws IOException {
    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }
 
    FTPFile[] subFiles = ftpClient.listFiles(dirToList);
 
    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                // skip parent directory and the directory itself
                continue;
            }
            String filePath = parentDir + "/" + currentDir + "/"
                    + currentFileName;
            if (currentDir.equals("")) {
                filePath = parentDir + "/" + currentFileName;
            }
 
            String newDirPath = saveDir + parentDir + File.separator
                    + currentDir + File.separator + currentFileName;
            if (currentDir.equals("")) {
                newDirPath = saveDir + parentDir + File.separator
                          + currentFileName;
            }
 
            if (aFile.isDirectory()) {
                // create the directory in saveDir
                File newDir = new File(newDirPath);
                boolean created = newDir.mkdirs();
                if (created) {
                    System.out.println("CREATED the directory: " + newDirPath);
                } else {
                    System.out.println("COULD NOT create the directory: " + newDirPath);
                }
 
                // download the sub directory
                downloadDirectory(ftpClient, dirToList, currentFileName,
                        saveDir);
            } else {
                // download the file
                boolean success = downloadSingleFile(ftpClient, filePath,
                        newDirPath);
                if (success) {
                    System.out.println("DOWNLOADED the file: " + filePath);
                } else {
                    System.out.println("COULD NOT download the file: "
                            + filePath);
                }
            }
        }
    }
}


public static boolean downloadSingleFile(FTPClient ftpClient,
        String remoteFilePath, String savePath) throws IOException {
    File downloadFile = new File(savePath);
     
    File parentDir = downloadFile.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdir();
    }
         
    OutputStream outputStream = new BufferedOutputStream(
            new FileOutputStream(downloadFile));
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        return ftpClient.retrieveFile(remoteFilePath, outputStream);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

}