Uploading to FTP using Java

user2526311 picture user2526311 · Jul 3, 2013 · Viewed 32.3k times · Source

I was just wondering if there was a simple way I could upload a small file to a ftp server. I've checked out Apache Commons Net library but that seems quite complicated to be honest. Is there any simpler way to upload a small file to ftp?

Ended up using the Apache Commons Net Library, wasn't too hard.

Answer

Loša picture Loša · Jul 3, 2013

From this link: Upload files to FTP server using URLConnection class. No external library necessary.

String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
String host = "www.myserver.com";
String user = "tom";
String pass = "secret";
String filePath = "E:/Work/Project.zip";
String uploadPath = "/MyProjects/archive/Project.zip";

ftpUrl = String.format(ftpUrl, user, pass, host, uploadPath);
System.out.println("Upload URL: " + ftpUrl);

try {
    URL url = new URL(ftpUrl);
    URLConnection conn = url.openConnection();
    OutputStream outputStream = conn.getOutputStream();
    FileInputStream inputStream = new FileInputStream(filePath);

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outputStream.close();

    System.out.println("File uploaded");
} catch (IOException ex) {
    ex.printStackTrace();
}