在执行java定时任务时,可能会操作ftp服务器文件,为此学习了apache的FTPClient,再此与大家一起分享
话不多说,直接上代码:
登陆:
//建立连接下载文件:
//地址,用户名,用户密码,端口(默认21)
public FTPUtil(String ftpHost, String ftpPassword,
String ftpUserName, int ftpPort) throws SocketException, IOException{
ftp=new FTPClient();
ftp.connect(ftpHost,ftpPort);
ftp.login(ftpUserName, ftpPassword);
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
System.out.println("连接成功");
}else{
System.out.println("连接失败");
}
}
//下载文件
//下载路径,保存路径,保存地址,保存文件名
public void download(String ftpPath, String name,String outurl,String fileName) throws IOException{
InputStream in=readConfigFileForFTP(ftpPath, name);
File file=new File(outurl,fileName);
FileOutputStream out =new FileOutputStream(file);
if (in != null) {
int b;
while((b = in.read()) != -1){
out.write(b);
}
}
in.close();
out.close();
}
//读取文件
//文件路径,文件名称,链接
public InputStream readConfigFileForFTP(String ftpPath, String fileName) {
InputStream in = null;
try {
ftp.setControlEncoding("UTF-8"); // 中文支持
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(ftpPath);
in = ftp.retrieveFileStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("读取文件失败,请联系管理员.");
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return in;
}
上传文件:
//上传文件
//上传路径,上传文件名,本地路径,本地文件名
public void upload(String path, String filename, String url, String fm) throws IOException{
File file=new File(url,fm);
InputStream in=new FileInputStream(file);
//由于传输文件名,所以将文件名编码转为"iso-8859-1"
filename=new String(filename.getBytes("UTF-8"),"iso-8859-1");
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, in);
in.close();
}
删除文件:
//删除文件
//文件全限定名称
public boolean remove(String srcFname) throws IOException{
//由于传输文件名,所以将文件名编码转为"iso-8859-1"
srcFname=new String(srcFname.getBytes("UTF-8"),"iso-8859-1");
return ftp.deleteFile(srcFname);
}
ps:看完后别着急走,留些意见吧!