有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过FTP在Java中上传文件

我正在尝试开发一个简单的java代码,它将一些内容从本地机器上传到服务器/另一台机器。我使用了下面的代码

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

但它在第11行显示错误,因为“无法实例化FtpClient类型”。 谁能帮我纠正一下吗


共 (3) 个答案

  1. # 1 楼答案

    我已经解决了这个例外。这是因为我的机器连接在一个不允许FTP连接的网络中。当我在一个私人加密狗中尝试它时,它起了作用

  2. # 2 楼答案

    如果您确实想要使用Sun类,请根据该类的JavaDoc使用FtpClient.create()

  3. # 3 楼答案

    您无法实例化它,因为sun。网ftp。FtpClient是抽象类

    我建议使用ApacheCommonsNet而不是使用sun。x个包裹。FTP客户端示例可以在here中找到