通过FTP上传文件在Java中(File upload in Java through FTP)

2019-06-26 15:28发布

我试着去开发一个简单的Java代码,将上传从本地机器的一些内容到服务器/另一machine.I用下面的代码

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”。 有人可以帮我如何纠正它。

Answer 1:

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

我建议使用Apache共享网络,而不是与sun.x包玩。 FTP客户端例如可以找到这里 。



Answer 2:

如果想使用Sun的类,使用FtpClient.create()按的JavaDoc这个类。



Answer 3:

因为我的机器连接的网络,其犯规让FTP connection.when我在它的工作的私人加密狗试图在我已经解决了exception.thats。



文章来源: File upload in Java through FTP
标签: java upload ftp