【问题标题】:File upload in Java through FTP通过 FTP 在 Java 中上传文件
【发布时间】:2012-07-29 03:54:48
【问题描述】:

我正在尝试开发一个简单的 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 类型”。 谁能帮我解决一下。

【问题讨论】:

标签: java upload ftp


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      你不能实例化它,因为 sun.net.ftp.FtpClient 是抽象类。

      我建议使用 Apache Commons Net 而不是使用 sun.x 包。 FTP客户端示例可以从here找到。

      【讨论】:

      • 尝试了您建议的链接。但收到错误“无法解析导入 org.apache”
      • 它不是 JDK 的一部分,它是外部库。因此,您还需要类路径中的库本身。你可以从这里下载:commons.apache.org/net/download_net.cgi
      • 这真的很有帮助.. 现在我已经做了类似这样的事情 FTPClient client = new FTPClient(); FileInputStream fis = null;尝试 { client.connect("一些主机名"); client.login("用户", "密码");字符串文件名 = "Touch.dat"; fis = new FileInputStream(文件名); client.storeFile(filename, fis); client.logout();当我给服务器主机及其用户名和密码时..它会抛出 java.net.UnknownHostException..关于这个有什么想法吗?
      猜你喜欢
      • 2012-02-22
      • 2013-03-21
      • 2012-04-26
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多