Home
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)
Java APIs for
Developers
Ofce formats and
Native Java Code
Free support and free
evaluation
[Link]
Java FTP le download tutorial and example
LastUpdatedon15July2015|
DownloadAsposeforallyourfileformatmanipulationneeds
Print
Email
WiththehelpofApacheCommonsNetAPI,itiseasytowriteJavacodefor
[Link],youwill
learnhowtoproperlyimplementJavacodetogetfilesdownloadedfromaserverviaFTP
[Link].
TableofContent
[Link]
[Link]
[Link]
[Link]
1. Apache Commons Net API for downloading
les by FTP protocol
[Link]
downloadingfilesfromaFTPserver:
booleanretrieveFile(Stringremote,OutputStreamlocal):This
methodretrievesaremotefilewhosepathisspecifiedbytheparameterremote,
[Link]
methodreturnstrueifoperationcompletedsuccessfully,[Link]
methodissuitableincasewedontcarehowthefileiswrittentodisk,justletthe
[Link]
OutputStreamtheafterthemethodreturns.
InputStreamretrieveFileStream(Stringremote):Thismethoddoesnot
useanOutputStream,insteaditreturnsanInputStreamwhichwecanuseto
[Link]
[Link]
method:
ThemethodcompletePendingCommand()mustbecalledafterwardto
finalizefiletransferandcheckitsreturnvaluetoverifyifthedownloadis
actuallydonesuccessfully.
WemustclosetheInputStreamexplicitly.
Whichmethodisusedsuitableforyou?Herearefewtips:
Thefirstmethodprovidesthesimplestwayfordownloadingaremotefile,asjust
passinganOutputStreamofthefilewillbewrittenondisk.
Thesecondmethodrequiresmorecodetobewritten,aswehavetocreatea
newOutputStreamforwritingfilescontentwhilereadingitsbytearraysfrom
[Link]
progressofthedownload,[Link]
[Link],wehavetocallthecompletePendingCommand()to
finalizethedownload.
BoththemethodsthrowanIOExceptionexception(oroneofitsdescendants,
FTPConnectionClosedExceptionandCopyStreamException).Therefore,
makesuretohandletheseexceptionswhencallingthemethods.
Inaddition,thefollowingtwomethodsmustbeinvokedbeforecallingthe
retrieveFile()andretrieveFileStream()methods:
voidenterLocalPassiveMode():thismethodswitchesdataconnectionmode
fromservertoclient(defaultmode)toclienttoserverwhichcanpassthrough
[Link].
booleansetFileType(intfileType):thismethodsetsfiletypetobe
transferred,[Link]
typetoFTP.BINARY_FILE_TYPE,ratherthanFTP.ASCII_FILE_TYPE.
2. The proper steps to download a le
HerearethestepstoproperlyimplementcodefordownloadingaremotefilefromaFTP
serverusingApacheCommonsNetAPIwhichisdiscussedsofar:
Connectandlogintotheserver.
Enterlocalpassivemodefordataconnection.
Setfiletypetobetransferredtobinary.
Constructpathoftheremotefiletobedownloaded.
CreateanewOutputStreamforwritingthefiletodisk.
Ifusingthefirstmethod(retrieveFile):
PasstheremotefilepathandtheOutputStreamasargumentsofthe
methodretrieveFile().
ClosetheOutputStream.
CheckreturnvalueofretrieveFile()toverifysuccess.
Ifusingthesecondmethod(retrieveFileStream):
RetrieveanInputStreamreturnedbythemethodretrieveFileStream().
RepeatedlyabytearrayfromtheInputStreamandwritethesebytesintothe
OutputStream,untiltheInputStreamisempty.
CallcompletePendingCommand()methodtocompletetransaction.
ClosetheopenedOutputStreamtheInputStream.
CheckreturnvalueofcompletePendingCommand()toverifysuccess.
Logoutanddisconnectfromtheserver.
3. Sample program code
Java APIs for Developers
Ofce formats and Native Java
Code Free support and free
evaluation
[Link]
Inthefollowingsampleprogram,usingbothmethodsisimplementedfortransferringa
[Link]:
1
2
3
4
5
6
7
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
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
[Link];
[Link];
[Link];
/**
*Aprogramdemonstrateshowtouploadfilesfromlocalcomputertoaremote
*FTPserverusingApacheCommonsNetAPI.
*@[Link]
*/
publicclassFTPDownloadFileDemo{
publicstaticvoidmain(String[]args){
Stringserver="[Link]";
intport=21;
Stringuser="user";
Stringpass="pass";
FTPClientftpClient=newFTPClient();
try{
[Link](server,port);
[Link](user,pass);
[Link]();
[Link](FTP.BINARY_FILE_TYPE);
//APPROACH#1:usingretrieveFile(String,OutputStream)
StringremoteFile1="/test/video.mp4";
FiledownloadFile1=newFile("D:/Downloads/video.mp4");
OutputStreamoutputStream1=newBufferedOutputStream(newFileOutputStream(downloadFile1)
booleansuccess=[Link](remoteFile1,outputStream1);
[Link]();
if(success){
[Link]("File#1hasbeendownloadedsuccessfully."
}
//APPROACH#2:usingInputStreamretrieveFileStream(String)
StringremoteFile2="/test/song.mp3";
FiledownloadFile2=newFile("D:/Downloads/song.mp3");
OutputStreamoutputStream2=newBufferedOutputStream(newFileOutputStream(downloadFile2)
InputStreaminputStream=[Link](remoteFile2);
byte[]bytesArray=newbyte[4096];
intbytesRead=1;
while((bytesRead=[Link](bytesArray))!=1){
[Link](bytesArray,0,bytesRead);
}
success=[Link]();
if(success){
[Link]("File#2hasbeendownloadedsuccessfully."
}
[Link]();
[Link]();
}catch(IOExceptionex){
[Link]("Error:"+[Link]());
[Link]();
}finally{
try{
if([Link]()){
[Link]();
[Link]();
}
}catch(IOExceptionex){
[Link]();
}
}
}
}
SAMSUNGEP
PG920IBUGUS
SAMSUNGWIRELESS
4. Compile and run the sample program
Tocompileandruntheprogram,youneedanApacheCommonsNetsjarlibraryfile
[Link]
CommonsNet.
[Link]
[Link].
Typethefollowingcommandtocompiletheprogram:
[Link]
Andtypethiscommandtoruntheprogram:
[Link]
NOTES:
[Link]
timeofwritingthisarticle,thelatestversionofApacheCommonsNetAPIis3.3,
[Link]
Fordownloadingawholedirectory,seethearticle:Howtodownloadacomplete
folderfromaFTPserver.
Anenhanced,swingbasedversion:Swingapplicationtodownloadfilesfrom
FTPserverwithprogressbar.
JavaNetworkProgramming,FourthEditionThisbookisamustreadfor
[Link]
toquicklyandeasilyaccomplishcommonnetworkingtaskssuchaswritingmulti
threadedservers,encryptingcommunications,broadcastingtothelocalnetwork,
andpostingdatatoserversideprograms.
Share this article:
FreeJavaBeginnerTutorialVideos(8,802+guysbenefited)
EMAILADDRESS:
FIRSTNAME:
you@[Link]
SENDME
John
Attachments:
[Link] [JavaFTPFileDownloadProgram] 2kB
Add comment
Email
Name
comment
500symbolsleft
Notifymeoffollowupcomments
Typethetext
Privacy&Terms
Send
Comments
0
#31vedanshi 2016081100:00
iamgettingthiserror:[Link]:Connectiontimedout:connect
[Link].connect0(NativeMethod)
[Link](UnknownSource)
[Link](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"[Link]
[Link]([Link])
Quote
#25Sara 2015111210:01
Hi,thankforthetutorial,
Ihavemanagedtoretrievecvsfiles,butforsomereasonthefilesareempty.
+2
Quote
#24Hacker
nice..
+2
2015100604:16
Quote
+1
#23Nam 2014121004:23
HiKrishanuDebnath,
Doyouneedsuchprogramordoyouwanttowritecode?
Iwrotesuchaprogrambeforeusingtherestart()methodoftheApacheCommons
[Link].
Quote
+2
#22KrishanuDebnath 2014121001:45
ineedajavaprogramtodownloadafileusingurl&inthatsameprogramihaveto
measurethefilesizebeforestartingthedownload&ifservergetdisconnected&
againistartthedownloadedthedownloadingstartsfromtheremainingpart..????
Quote
1
Refreshcommentslist
RSSfeedforcommentstothispost
JComments
JavaTipsEveryDayAboutAdvertiseContributeContactTermsofUsePrivacyPolicySiteMapNewsletter
[Link]