java Java文件通过FTP上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11739153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:11:56  来源:igfitidea点击:

File upload in Java through FTP

javauploadftp

提问by Satheesh

Im trying to develop a simple java code which will upload some contents from local machine to a server/another machine.I used the below code

我正在尝试开发一个简单的 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());
   }
 }
}

But it is showing error in Line 11 as 'Cannot instantiate the type FtpClient'. Can some one help me how to rectify it.

但它在第 11 行显示错误为“无法实例化 FtpClient 类型”。有人可以帮助我如何纠正它。

采纳答案by Mikko Maunu

You cannot instantiate it because sun.net.ftp.FtpClient is abstract class.

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

I suggest using Apache Commons Net instead of playing with sun.x packages. FTP client example can be found from here.

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

回答by mthmulders

If you dowant to use the Sun classes, use FtpClient.create(), as per the JavaDoc for this class.

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

回答by Satheesh

i have resolved the exception.thats because my machine is connected in a network which doesnt allow FTP connection.when i tried it in a private dongle it worked.

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