通过FTP上传Java文件 [英] File upload in Java through FTP

查看:194
本文介绍了通过FTP上传Java文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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'。
有人可以帮我解决问题。

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

推荐答案

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

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

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

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

这篇关于通过FTP上传Java文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆