Java: Accessing a File from an FTP Server

前端 未结 2 1505
醉酒成梦
醉酒成梦 2021-02-05 21:38

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 de

相关标签:
2条回答
  • 2021-02-05 22:13

    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.

    0 讨论(0)
  • 2021-02-05 22:14

    if you use URI with file you can use your code but , but when you want to use ftp so you need to this kind of code; code list the name of the files under your ftp server

    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 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题