使用 Java 上传到 FTP

Uploading to FTP using Java(使用 Java 上传到 FTP)
本文介绍了使用 Java 上传到 FTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我只是想知道是否有一种简单方法可以将小文件上传到 ftp 服务器.我已经查看了 Apache Commons Net 库,但老实说这似乎相当复杂.有没有更简单的方法可以把小文件上传到ftp?

I was just wondering if there was a simple way I could upload a small file to a ftp server. I've checked out Apache Commons Net library but that seems quite complicated to be honest. Is there any simpler way to upload a small file to ftp?

最终使用了 Apache Commons Net Library,并不太难.

Ended up using the Apache Commons Net Library, wasn't too hard.

推荐答案

来自这个链接:使用 URLConnection 类上传文件到 FTP 服务器.无需外部库.

From this link: Upload files to FTP server using URLConnection class. No external library necessary.

String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
String host = "www.myserver.com";
String user = "tom";
String pass = "secret";
String filePath = "E:/Work/Project.zip";
String uploadPath = "/MyProjects/archive/Project.zip";

ftpUrl = String.format(ftpUrl, user, pass, host, uploadPath);
System.out.println("Upload URL: " + ftpUrl);

try {
    URL url = new URL(ftpUrl);
    URLConnection conn = url.openConnection();
    OutputStream outputStream = conn.getOutputStream();
    FileInputStream inputStream = new FileInputStream(filePath);

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outputStream.close();

    System.out.println("File uploaded");
} catch (IOException ex) {
    ex.printStackTrace();
}

这篇关于使用 Java 上传到 FTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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?)