jar包:rt.jar
注:JDK1.5包下的 sun.net.ftp.FtpClient
以下都是方法调用
private FtpClient ftpClient = null;
public static void main(String[] args) {
List fileList = ftpClient.getFileList(ftpdir);//服务器路径
//要下载的远程文件
String remoteFile = "./aaa/" + "文件名".replace("/","");
//本地生成的文件路径
String localFile = "./bbb/" + "文件名" + ".txt";
connectServer("服务器地址","登录用户","登录密码","文件夹,空代表根目录");
//建立本地目录(文件夹)
File file = new File(localFile);
if(!file.getParentFile().exists()) {
boolean result = file.getParentFile().mkdirs();
log.info(file.getParentFile().getPath() + "不存在,建立新目录,创建结果: " + result);
}
//循环遍历需要下载的文件
for (int j = 0; j<fileList.size();j++) {
if(remoteFile.equals(fileList.get(j))) {
download1(remoteFile ,localFile );
}
}
//关闭ftp连接
ftpClient。close();
br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
//读取文件数据数据插入表
String line = null;
StringBuffer strBuffer = new StringBuffer();
while((line = br.readLine()) != null) {
strBuffer.append(line+"/n");
String[] strs = line.split("分隔符");
//插入数据库
str[0];str[1]...
}catch(Exception e) {
e.printStackTrace();
} finally {
br.close();
}
return "成功";
}
/**
*ftp 连接服务器
*server 服务器地址
user:服务器登录用户名
password:服务器登录密码
path 文件夹,空代表根目录
*/
public void connectServer(String server,String user,String password,String path) throws IOException{
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user,password);
ftpCd(path);
//用二进制上传下载
//ftpClient.binary();
//用ASCII码上传下载
ftpClient.ascii();
}
/**
*更改ftp服务器路径
sRemotePath 文件夹,空代表根目录
*/
public void ftpCd(String sRemotePath) throws IOException{
if(sRemotePath.length() != 0){
ftpClient.cd(sRemotePath);
}
}
/**
*取得某个目录下所有文件列表
path:目录路径
@return 文件列表
*/
public long download(String path){
List<String> list = new ArrayList();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(ftpClient.nameList(path)));
String filename = "";
while(filename = br.readLine() != null) {
list.add(filename);
}
} catch(Exception e) {
e.printStackTrace();
}
return list;
}
/**
*从ftp下载文件到本地
*@Return 成功下载,返回文件大小
filenmae:服务器上的文件名
newfilename:本地生成的文件名
*/
public long download1(String filename,String newfilename) throws {
long result = 0;
TelnetInputStream is = null;
FileOutputStream = null;
try{
is = ftpClient.get(filename);
java.io.File outfile = new File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while((c = is.read(bytes) != -1)){
os.write(bytes,0,c);
result = result+c;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(is != null) {
is.close();
}
if(os != null) {
os.close();
}
}
}