Uploading a file in Java via FTP

I am trying to develop simple Java code that will download some content from a local machine to a server / another machine. I used the code below

import sun.net.ftp.*; import java.io.*; public class SftpUpload { public static void main(String args[]) { String hostname = "some.remote.machine"; //Remote FTP server: Change this String username = "user"; //Remote user name: Change this String password = "start123"; //Remote user password: Change this String upfile = args[0]; //File to upload passed on command line String remdir = "/home/user"; //Remote directory for file upload FtpClient ftp = new FtpClient(); try { ftp.openServer(hostname); //Connect to FTP server ftp.login(username, password); //Login ftp.binary(); //Set to binary mode transfer ftp.cd(remdir); //Change to remote directory File file = new File(upfile); OutputStream out = ftp.put(file.getName()); //Start upload InputStream in = new FileInputStream(file); byte c[] = new byte[4096]; int read = 0; while ((read = in.read(c)) != -1 ) { out.write(c, 0, read); } //Upload finished in.close(); out.close(); ftp.closeServer(); //Close connection } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } 

But it shows the error on line 11 as "Unable to create an instance of type FtpClient." Can someone help me how to fix this.

+4
source share
3 answers

You cannot create an instance because sun.net.ftp.FtpClient is an abstract class.

I suggest using Apache Commons Net instead of playing with the sun.x package. An example FTP client can be found here .

+2
source

If you want to use Sun classes, use FtpClient.create() according to the JavaDoc for this class.

+2
source

I resolved the exception. This is because my machine is connected to a network that does not support FTP connection. When I tried it in a private dongle, it worked.

0
source

All Articles