Uploading to FTP using Java

后端 未结 3 1473
死守一世寂寞
死守一世寂寞 2020-12-13 22:30

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 quit

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 22:58

    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();
    }
    

提交回复
热议问题