解决FTPClient上传文件为空,显示0字节
生活随笔
收集整理的這篇文章主要介紹了
解决FTPClient上传文件为空,显示0字节
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JAVA使用FTPClient上傳文件時(shí)總是為空,而使用FileZilla客戶端時(shí)卻不會。
后來查了下資料,FTP服務(wù)器有被動模式和主動模式。(具體查另外資料)
在JAVA中將FTPClient設(shè)置為被動模式即可解決問題。
?
import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient;import java.io.File; import java.io.FileInputStream;/*** Created by Administrator on 2018/4/13.*/ public class FtpUtil {public void testFTPClient() throws Exception {try {//創(chuàng)建一個(gè)FTPClient對象FTPClient ftpClient = new FTPClient();//創(chuàng)建ftp鏈接ftpClient.connect("***.***.***.***", 21);//登錄ftp,使用用戶名和密碼ftpClient.login("****", "****");//讀取本地文件FileInputStream inputStream = new FileInputStream(new File("filePath"));//設(shè)置為被動模式(如上傳文件夾成功,不能上傳文件,注釋這行,否則報(bào)錯(cuò)refused:connect )ftpClient.enterLocalPassiveMode();//設(shè)置上傳路徑ftpClient.changeWorkingDirectory("FTP服務(wù)器文件目錄");//修改上傳文件格式ftpClient.setFileType(FTP.BINARY_FILE_TYPE);System.out.println("1");//上傳文件ftpClient.storeFile("hello1.jpg", inputStream);System.out.println("2");//關(guān)閉鏈接ftpClient.logout();} catch (Exception e) {e.printStackTrace();throw e;}} }?
補(bǔ)充:
調(diào)用FTPClient.enterLocalPassiveMode();這個(gè)方法的意思就是每次數(shù)據(jù)連接之前,ftp client告訴ftp server開通一個(gè)端口來傳輸數(shù)據(jù)。為什么要這樣做呢,因?yàn)閒tp server可能每次開啟不同的端口來傳輸數(shù)據(jù),但是在linux上,由于安全限制,可能某些端口沒有開啟,所以就出現(xiàn)阻塞。
到此問題圓滿解決!
總結(jié)
以上是生活随笔為你收集整理的解决FTPClient上传文件为空,显示0字节的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net2.0跨域问题
- 下一篇: Anaconda安装第三方包(whl文件