Java FTP File Download Tutorial and Example
Java FTP File Download Tutorial and Example
Java FTP File Download Tutorial and Example
JavaCore
JavaSE
JavaEE
Frameworks
IDEs
Servers
Coding
Books
Videos
JavaSkillsTest
c Home
JavaSE
Networking
Adsby Google
DownloadZipFile
DownloadIt
FTP
Search...
Search...
CATERPILLAR
CATERPILLARCATS40
RUGGEDWATERPROOF
SMARTPHONE
FeaturedBooks
JavaCodingGuidelines:
Recommendationsfor
ReliableandSecure
Programs(SEISeriesin
SoftwareEngineering)
HeadFirstDesignPatterns
JavaConcurrencyinPractice
JavaPerformance
JavaPuzzlers:Traps,Pitfalls,
andCornerCases
HeadFirstObjectOriented
AnalysisandDesign
CleanCode:AHandbookof
AgileSoftwareCraftsmanship
AlgorithmsUnlocked
DataStructuresand
AlgorithmAnalysisinJava
(3rdEdition)
Refactoring:Improvingthe
Refactoring:Improvingthe
DesignofExistingCode
ThePragmaticProgrammer:
FromJourneymantoMaster
CodeComplete:APractical
HandbookofSoftware
Construction,SecondEdition
CrackingtheCoding
Interview:150Programming
QuestionsandSolutions
TheCleanCoder:ACodeof
ConductforProfessional
Programmers(RobertC.
MartinSeries)
www.aspose.com
WiththehelpofApacheCommonsNetAPI,itiseasytowriteJavacodefor
downloadingafilefromaremoteFTPservertolocalcomputer.Inthisarticle,youwill
learnhowtoproperlyimplementJavacodetogetfilesdownloadedfromaserverviaFTP
protocol.Aworkingsampleprogramalsoprovided.
TableofContent
1.ApacheCommonsNetAPIfordownloadingfilesbyFTPprotocol
2.Theproperstepstodownloadafile
3.Sampleprogramcode
4.Compileandrunthesampleprogram
methodreturnstrueifoperationcompletedsuccessfully,orfalseotherwise.This
methodissuitableincasewedontcarehowthefileiswrittentodisk,justletthe
systemusethegivenOutputStreamtowritethefile.Weshouldclose
OutputStreamtheafterthemethodreturns.
InputStreamretrieveFileStream(Stringremote):Thismethoddoesnot
useanOutputStream,insteaditreturnsanInputStreamwhichwecanuseto
readbytesfromtheremotefile.Thismethodgivesusmorecontrolonhowto
readandwritethedata.Buttherearetwoimportantpointswhenusingthis
method:
ThemethodcompletePendingCommand()mustbecalledafterwardto
finalizefiletransferandcheckitsreturnvaluetoverifyifthedownloadis
actuallydonesuccessfully.
WemustclosetheInputStreamexplicitly.
Whichmethodisusedsuitableforyou?Herearefewtips:
Thefirstmethodprovidesthesimplestwayfordownloadingaremotefile,asjust
passinganOutputStreamofthefilewillbewrittenondisk.
Thesecondmethodrequiresmorecodetobewritten,aswehavetocreatea
newOutputStreamforwritingfilescontentwhilereadingitsbytearraysfrom
thereturnedInputStream.Thismethodisusefulwhenwewanttomeasure
progressofthedownload,i.e.howmanypercentagesofthefilehavebeen
transferred.Inaddition,wehavetocallthecompletePendingCommand()to
finalizethedownload.
BoththemethodsthrowanIOExceptionexception(oroneofitsdescendants,
FTPConnectionClosedExceptionandCopyStreamException).Therefore,
makesuretohandletheseexceptionswhencallingthemethods.
Inaddition,thefollowingtwomethodsmustbeinvokedbeforecallingthe
retrieveFile()andretrieveFileStream()methods:
voidenterLocalPassiveMode():thismethodswitchesdataconnectionmode
fromservertoclient(defaultmode)toclienttoserverwhichcanpassthrough
firewall.Theremightbesomeconnectionissuesifthismethodisnotinvoked.
booleansetFileType(intfileType):thismethodsetsfiletypetobe
transferred,eitherasASCIItextfileorbinaryfile.Itisrecommendedtosetfile
typetoFTP.BINARY_FILE_TYPE,ratherthanFTP.ASCII_FILE_TYPE.
PasstheremotefilepathandtheOutputStreamasargumentsofthe
methodretrieveFile().
ClosetheOutputStream.
CheckreturnvalueofretrieveFile()toverifysuccess.
Ifusingthesecondmethod(retrieveFileStream):
RetrieveanInputStreamreturnedbythemethodretrieveFileStream().
RepeatedlyabytearrayfromtheInputStreamandwritethesebytesintothe
OutputStream,untiltheInputStreamisempty.
CallcompletePendingCommand()methodtocompletetransaction.
ClosetheopenedOutputStreamtheInputStream.
CheckreturnvalueofcompletePendingCommand()toverifysuccess.
Logoutanddisconnectfromtheserver.
Inthefollowingsampleprogram,usingbothmethodsisimplementedfortransferringa
filefromtheFTPservertolocalcomputer.Hereistheprogramssourcecode:
1
2
3
4
5
6
7
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
importjava.io.OutputStream;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
/**
*Aprogramdemonstrateshowtouploadfilesfromlocalcomputertoaremote
*FTPserverusingApacheCommonsNetAPI.
*@authorwww.codejava.net
*/
publicclassFTPDownloadFileDemo{
publicstaticvoidmain(String[]args){
Stringserver="www.myserver.com";
intport=21;
Stringuser="user";
Stringpass="pass";
FTPClientftpClient=newFTPClient();
try{
ftpClient.connect(server,port);
ftpClient.login(user,pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//APPROACH#1:usingretrieveFile(String,OutputStream)
StringremoteFile1="/test/video.mp4";
FiledownloadFile1=newFile("D:/Downloads/video.mp4");
OutputStreamoutputStream1=newBufferedOutputStream(newFileOutputStream(downloadFile1)
booleansuccess=ftpClient.retrieveFile(remoteFile1,outputStream1);
outputStream1.close();
if(success){
System.out.println("File#1hasbeendownloadedsuccessfully."
}
//APPROACH#2:usingInputStreamretrieveFileStream(String)
StringremoteFile2="/test/song.mp3";
FiledownloadFile2=newFile("D:/Downloads/song.mp3");
OutputStreamoutputStream2=newBufferedOutputStream(newFileOutputStream(downloadFile2)
InputStreaminputStream=ftpClient.retrieveFileStream(remoteFile2);
byte[]bytesArray=newbyte[4096];
intbytesRead=1;
while((bytesRead=inputStream.read(bytesArray))!=1){
outputStream2.write(bytesArray,0,bytesRead);
}
success=ftpClient.completePendingCommand();
if(success){
System.out.println("File#2hasbeendownloadedsuccessfully."
}
outputStream2.close();
inputStream.close();
}catch(IOExceptionex){
System.out.println("Error:"+ex.getMessage());
ex.printStackTrace();
}finally{
try{
if(ftpClient.isConnected()){
ftpClient.logout();
ftpClient.disconnect();
}
}catch(IOExceptionex){
ex.printStackTrace();
}
}
}
}
SAMSUNGEP
PG920IBUGUS
SAMSUNGWIRELESS
Andtypethiscommandtoruntheprogram:
javacpcommonsnetVERSION.jar.FTPDownloadFileDemo
NOTES:
YouneedtoreplaceVERSIONbytheactualversionnumberofthejarfile.Atthe
timeofwritingthisarticle,thelatestversionofApacheCommonsNetAPIis3.3,
hencecommonsnet3.3.jar
Fordownloadingawholedirectory,seethearticle:Howtodownloadacomplete
folderfromaFTPserver.
Anenhanced,swingbasedversion:Swingapplicationtodownloadfilesfrom
FTPserverwithprogressbar.
JavaNetworkProgramming,FourthEditionThisbookisamustreadfor
Javanetworkingdevelopment.YoulllearnhowtouseJavasnetworkclasslibrary
toquicklyandeasilyaccomplishcommonnetworkingtaskssuchaswritingmulti
threadedservers,encryptingcommunications,broadcastingtothelocalnetwork,
andpostingdatatoserversideprograms.
FreeJavaBeginnerTutorialVideos(8,802+guysbenefited)
EMAILADDRESS:
FIRSTNAME:
you@domain.com
SENDME
John
Attachments:
FTPDownloadFileDemo.java [JavaFTPFileDownloadProgram] 2kB
Add comment
Name
comment
500symbolsleft
Notifymeoffollowupcomments
Typethetext
Privacy&Terms
Send
Comments
0
#31vedanshi 2016081100:00
iamgettingthiserror:java.net.ConnectException:Connectiontimedout:connect
atjava.net.DualStackPlainSocketImpl.connect0(NativeMethod)
atjava.net.DualStackPlainSocketImpl.socketConnect(UnknownSource)
atjava.net.AbstractPlainSocketImpl.doConnect(UnknownSource)
Quote
#30Cristiane 2016072319:03
timoartigo,timoexemplo!Funcionouperfeitamentenaminhaaplicao.
0
Quote
#29Evandro 2016072108:32
Muitobom...euestavacomproblemasembaixarimagensdoFTPecomo
exemplodoretriveFIleStreamFuncionou!!
Quote
+2
#28Rod 2016020409:20
FTPDemoExcellentapp
Quote
#27naser
tkankyou
+4
2016010620:19
Quote
+2
#26Sara 2015111210:06
Igotthiserror:
Exceptioninthread"main"java.lang.NullPointerException
atImpFileFromFtp.main(ImpFileFromFtp.java:47)
Quote
#25Sara 2015111210:01
Hi,thankforthetutorial,
Ihavemanagedtoretrievecvsfiles,butforsomereasonthefilesareempty.
+2
Quote
#24Hacker
nice..
+2
2015100604:16
Quote
+1
#23Nam 2014121004:23
HiKrishanuDebnath,
Doyouneedsuchprogramordoyouwanttowritecode?
Iwrotesuchaprogrambeforeusingtherestart()methodoftheApacheCommons
NetFTPAPI.Emailmeifyouareinterested.
Quote
+2
#22KrishanuDebnath 2014121001:45
ineedajavaprogramtodownloadafileusingurl&inthatsameprogramihaveto
measurethefilesizebeforestartingthedownload&ifservergetdisconnected&
againistartthedownloadedthedownloadingstartsfromtheremainingpart..????
Quote
1
Refreshcommentslist
RSSfeedforcommentstothispost
JComments
JavaTipsEveryDayAboutAdvertiseContributeContactTermsofUsePrivacyPolicySiteMapNewsletter
Copyright20122016bywww.codejava.net