本文介紹了使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!