通过 FTP 在 Java 中上传文件

File upload in Java through FTP(通过 FTP 在 Java 中上传文件)
本文介绍了通过 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 中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Android sdk 18 TextView gravity doesn#39;t work vertically(Android sdk 18 TextView 重力不能垂直工作)
Java android: appending a newline using TextView(Java android:使用 TextView 添加换行符)
How to create simple Android TextView and display text on it using java code?(如何使用 java 代码创建简单的 Android TextView 并在其上显示文本?)
Add opaque quot;shadowquot; (outline) to Android TextView(添加不透明的“阴影(大纲)到 Android TextView)
Android: Creating a Circular TextView?(Android:创建一个圆形 TextView?)
Android - set TextView TextStyle programmatically?(Android - 以编程方式设置 TextView TextStyle?)