Search code examples
javajava-7urlconnectionftps

URLConnection with FTPS


Is it possible to change the current sourcecode so I can use FTPS?:

InputStream in = new URL(url).openStream();
OutputStream out = new     URL("ftp://"+user+":"+password+"@"+server+""+dir+""+filename_real_string).openConnection().get    OutputStream();
byte[] buffer = new byte[16384];
while ((r=in.read(buffer))>=0) {
  out.write(buffer, 0, r);
}
in.close();
out.close(); 

Is it possible without any additional libraries or if not, which library suits best?


Solution

  • You can use: org.apache.commons.net.ftp.FTPSClient

    Example to use it:

    public static void main(String[] args) {
        FTPSClient ftp = new FTPSClient();
        String host = "server.com";
        int port = 2121;
        String folderName = "dir";
        String username = "user";
        String password = "password";
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            InputStream fis = new FileInputStream("../filename_src.txt");
    
            ftp.storeFile("/" + folderName + "/filename_dest.xml", fis);
            fis.close();
    
            ftp.logout();
            ftp.disconnect();
        } catch (SocketException ex) {
            Logger.getLogger(FTPSendMessage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FTPSendMessage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }