JAVA实现FTP文件及目录

使用开源项目:ftp4j

http://www.sauronsoftware.it/projects/ftp4j/

 

import
 java.io.File;

import
 it.sauronsoftware.ftp4j.FTPClient;

import
 it.sauronsoftware.ftp4j.FTPFile;


public
 
class
 JavaFtp {

private
 FTPClient client 
=
null
;

public
 
void
 init(){

try
 {
client 
=
 
new
 FTPClient();
client.connect(
"
192.168.1.248
"
, 
21
);
client.login(
"
db2inst1
"
, 
"
db2inst1
"
);
} 
catch
 (Exception e) {
e.printStackTrace();
}
}

public
 
static
 
void
 main(String[] args) {

try
 {
JavaFtp javaFtp
=
new
 JavaFtp();
javaFtp.init();
javaFtp.download(
"
E://test
"
, 
"
/test/
"
);
javaFtp.close();
} 
catch
 (Exception e) {
e.printStackTrace();
}
}

public
 
void
 download(String localpath,String clientpath){

try
 { 

if
(clientpath
!=
null
&&
clientpath.length()
>=
0
){
client.changeDirectory(clientpath);
}
FTPFile[] list 
=
 client.list();


for
(
int
 i
=
0
;i
<
list.length;i
++
){
FTPFile file 
=
 list[i];
System.out.println(file.getType());

if
(file.getType()
==
FTPFile.TYPE_DIRECTORY){
File temp
=
new
 File(localpath
+
File.separator
+
file.getName());

if
(
!
temp.exists()){
temp.mkdir();
}
download(localpath
+
File.separator
+
file.getName(),file.getName());
}

else
 
if
(file.getType()
==
FTPFile.TYPE_FILE){
File localfile
=
new
 File(localpath
+
File.separator
+
file.getName());
client.download(file.getName(), localfile);
}
} 
} 
catch
 (Exception e) {
e.printStackTrace();
}
}

public
 
void
 close(){

try
 { 
client.disconnect(
true
);
} 
catch
 (Exception e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(java)