java 循环删除ftp_java连接FTP、删除、下载文件的方法-程序员宅基地

技术标签: java 循环删除ftp  

本文共例举了二个连接FTP的方法,可以下载删除FTP上的文件,代码有点凌乱

JAVA自带的方法

importjava.io.BufferedInputStream;

importjava.io.DataInputStream;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.Properties;

importjava.util.StringTokenizer;

importorg.apache.commons.lang.StringUtils;

importorg.apache.log4j.Logger;

importsun.net.TelnetInputStream;

importsun.net.TelnetOutputStream;

importsun.net.ftp.FtpClient;

/*

* Copyright (C) 2011-2014 dshine.com

* All rights reserved.

*/

/**

*@authorWiker Yong Email:

*@date2014-8-19下午2:00:58

*@version1.0-SNAPSHOT

*/

publicclassJavaFtpClient{

privateStringip="";

privateStringusername="";

privateStringpassword="";

privateintport=-1;

privateStringpath="";

FtpClientftpClient=null;

OutputStreamos=null;

FileInputStreamis=null;

staticStringcurFolder=System.getProperty("user.dir");

privatefinalstaticLoggerlog=Logger.getLogger(JavaFtpClient.class);

// LogInfologinfo = new LogInfo();

publicJavaFtpClient(StringserverIP,Stringusername,Stringpassword){

this.ip=serverIP;

this.username=username;

this.password=password;

}

publicJavaFtpClient(StringserverIP,intport,Stringusername,Stringpassword){

this.ip=serverIP;

this.username=username;

this.password=password;

this.port=port;

}

publicvoidsetPath(Stringpath)

throwsIOException{

if(ftpClient==null){

this.path=path;

}else{

ftpClient.cd(path);

}

}

/**

*连接ftp服务器

*

*@throwsIOException

*/

publicbooleanconnectServer(){

if(ftpClient!=null){

returntrue;

}

ftpClient=newFtpClient();

try{

if(this.port!=-1){

ftpClient.openServer(this.ip,this.port);

}else{

ftpClient.openServer(this.ip);

}

ftpClient.login(this.username,this.password);

if(this.path.length()!=0){

ftpClient.cd(this.path);//

path是ftp服务下主目录的子目录

}

ftpClient.binary();//用2进制上传、下载

log.info("FTP已登录到\""+ftpClient.pwd()+"\"目录");

// loginfo.appendLog("FTP已登录到\"" + ftpClient.pwd() + "\"目录");

returntrue;

}catch(IOExceptione){

log.error(e.getMessage(),e);

returnfalse;

}

}

/**

*断开与ftp服务器连接

*

*@throwsIOException

*/

publicbooleancloseServer(){

try{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

if(ftpClient!=null){

ftpClient.closeServer();

}

log.info("已从服务器断开");

// loginfo.appendLog("已从服务器断开");

returntrue;

}catch(IOExceptione){

e.printStackTrace();

returnfalse;

}

}

/**

*检查文件夹在当前目录下是否存在

*

*@paramdir

*@return

*/

publicbooleanisDirExist(Stringdir){

Stringpwd="";

try{

pwd=ftpClient.pwd();

ftpClient.cd(dir);

ftpClient.cd(pwd);

}catch(Exceptione){

returnfalse;

}

returntrue;

}

publicbooleanrename(Stringstr1,Stringstr2)

throwsIOException{

Stringfile1="";

Stringfile2="";

Stringfolder1="";

Stringfolder2="";

file1=str1.substring(str1.lastIndexOf("/")+1,str1.length());

file2=str2.substring(str2.lastIndexOf("/")+1,str2.length());

folder1=str1.substring(0,str1.lastIndexOf("/")+1);

folder2=str2.substring(0,str2.lastIndexOf("/")+1);

if(!isDirExist(folder2)){

createDir(folder2);

}

ftpClient.rename(str1,str2);

Listl=this.getFileList(folder2);

for(inti=0;i

if(l.get(i).toString().indexOf(file2)>0){

returntrue;

}

}

returnfalse;

}

publicvoidsendCMD(Stringcmd)

throwsIOException{

ftpClient.sendServer(cmd);

log.info(cmd.replaceAll("\r\n","\\\\r\\\\n"));

intreply=ftpClient.readServerResponse();

log.info("Server Response:"+reply);

// log.info(reply);

}

/**

*在当前目录下创建文件夹

*

*@paramdir

*@return

*@throwsException

*/

privatebooleancreateDir(Stringdir){

try{

ftpClient.ascii();

StringTokenizers=newStringTokenizer(dir,"/");//

sign

s.countTokens();

StringpathName="";//ftpClient.pwd();

while(s.hasMoreElements()){

pathName=pathName+"/"+(String)s.nextElement();

if(this.isDirExist(pathName)){

continue;

}

try{

ftpClient.sendServer("MKD

"+pathName+"\r\n");

}catch(Exceptione){

e=null;

returnfalse;

}

ftpClient.readServerResponse();

}

ftpClient.binary();

returntrue;

}catch(IOExceptione1){

e1.printStackTrace();

returnfalse;

}

}

/**

* ftp上传如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

*@paramfilename

*要上传的文件(或文件夹)名

*@return

*@throwsException

*/

publicbooleanupload(Stringfilename){

Stringnewname="";

if(filename.indexOf("/")>-1){

newname=filename.substring(filename.lastIndexOf("/")+1);

}else{

newname=filename;

}

returnupload(filename,newname);

}

/**

* ftp上传如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

*@paramfileName

*要上传的文件(或文件夹)名

*@paramnewName

*服务器段要生成的文件(或文件夹)名

*@return

*/

publicbooleanupload(StringfileName,StringnewName){

try{

Stringsavefilename=newString(fileName.getBytes("ISO-8859-1"),"GBK");

Filefile_in=newFile(savefilename);//打开本地待长传的文件

if(!file_in.exists()){

thrownewException("此文件或文件夹["+file_in.getName()+"]有误或不存在!");

}

if(file_in.isDirectory()){

upload(file_in.getPath(),newName,ftpClient.pwd());

}else{

uploadFile(file_in.getPath(),newName);

}

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

returntrue;

}catch(Exceptione){

e.printStackTrace();

System.err.println("Exception

ein Ftp upload(): "+e.toString());

returnfalse;

}finally{

try{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

}catch(IOExceptione){

e.printStackTrace();

}

}

}

/**

*真正用于上传的方法

*

*@paramfileName

*@paramnewName

*@parampath

*@throwsException

*/

privatevoidupload(StringfileName,StringnewName,Stringpath)

throwsException{

Stringsavefilename=newString(fileName.getBytes("ISO-8859-1"),"GBK");

Filefile_in=newFile(savefilename);//打开本地待长传的文件

if(!file_in.exists()){

thrownewException("此文件或文件夹["+file_in.getName()+"]有误或不存在!");

}

if(file_in.isDirectory()){

if(!isDirExist(newName)){

createDir(newName);

}

ftpClient.cd(newName);

FilesourceFile[]=file_in.listFiles();

for(inti=0;i

if(!sourceFile[i].exists()){

continue;

}

if(sourceFile[i].isDirectory()){

this.upload(sourceFile[i].getPath(),sourceFile[i].getName(),path+"/"

+newName);

}else{

this.uploadFile(sourceFile[i].getPath(),sourceFile[i].getName());

}

}

}else{

uploadFile(file_in.getPath(),newName);

}

ftpClient.cd(path);

}

/**

* upload上传文件

*

*@paramfilename

*要上传的文件名

*@paramnewname

*上传后的新文件名

*@return-1文件不存在>=0

成功上传,返回文件的大小

*@throwsException

*/

publiclonguploadFile(Stringfilename,Stringnewname)

throwsException{

longresult=0;

TelnetOutputStreamos=null;

FileInputStreamis=null;

try{

java.io.Filefile_in=newjava.io.File(filename);

if(!file_in.exists()){

return-1;

}

os=ftpClient.put(newname);

result=file_in.length();

is=newFileInputStream(file_in);

byte[]bytes=newbyte[1024];

intc;

while((c=is.read(bytes))!=-1){

os.write(bytes,0,c);

}

}finally{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

}

returnresult;

}

/**

*从ftp下载文件到本地

*

*@paramfilename

*服务器上的文件名

*@paramnewfilename

*本地生成的文件名

*@return

*@throwsException

*/

publiclongdownloadFile(Stringfilename,Stringnewfilename){

longresult=0;

TelnetInputStreamis=null;

FileOutputStreamos=null;

try{

is=ftpClient.get(filename);

java.io.Fileoutfile=newjava.io.File(newfilename);

log.info("Download File:"+outfile.getPath());

os=newFileOutputStream(outfile);

byte[]bytes=newbyte[1024];

intc;

while((c=is.read(bytes))!=-1){

os.write(bytes,0,c);

result=result+c;

}

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

}catch(IOExceptione){

e.printStackTrace();

}

}

returnresult;

}

/**

*取得相对于当前连接目录的某个目录下所有文件列表

*

*@parampath

*@return

*/

publicListgetFileList(Stringpath){

Listlist=newArrayList();

DataInputStreamdis;

try{

log.info(this.path+path);

dis=newDataInputStream(ftpClient.nameList(this.path+path));

Stringfilename="";

while((filename=dis.readLine())!=null){

Stringsfilename=newString(filename.getBytes("ISO-8859-1"),"utf-8");

list.add(sfilename);

}

}catch(IOExceptione){

e.printStackTrace();

}

returnlist;

}

publicstaticvoidmain(String[]args)

throwsIOException{

workPath=JavaFtpClient.class.getClass().getResource("/").getPath();

StringtempFolder=getPropertiesValueByKey(workPath+"/application.properties",

"download.path");

Filefile=newFile(tempFolder);

if(!file.exists()){

file.mkdir();

}

StringftpIp=getPropertiesValueByKey(workPath+"/application.properties","ftp.ip");

Stringport=getPropertiesValueByKey(workPath+"/application.properties","ftp.port");

Stringuser=getPropertiesValueByKey(workPath+"/application.properties","ftp.user");

Stringpassword=getPropertiesValueByKey(workPath+"/application.properties",

"ftp.password");

Stringsleep=getPropertiesValueByKey(workPath+"/application.properties","sleep.time");

sleep=StringUtils.defaultIfEmpty(sleep,"3600");

while(true){

JavaFtpClientftp=newJavaFtpClient(ftpIp,Integer.valueOf(port),user,password);

ftp.setPath("/");

ftp.connectServer();

// boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");

// log.info(result ? "上传成功!" : "上传失败!");

Listlist=ftp.getFileList("/");

for(inti=0;i

// String name = newString(list.get(i).toString().getBytes("UTF-8"), "iso-8859-1");

Stringname=list.get(i).toString();

// log.info(name);

if(!ftp.isDirExist(name)){

ftp.downloadFile(

name,

tempFolder+"\\"

+name.substring(name.lastIndexOf("/")+1,name.length()));

ftp.sendCMD("DELE "+name.substring(name.lastIndexOf("/")+1,name.length())

+"\r\n");

}

}

ftp.closeServer();

try{

log.info("休眠"+sleep

+"秒");

Thread.sleep(Integer.valueOf(sleep)*1000);

}catch(NumberFormatExceptione){

//TODOAuto-generated catch block

e.printStackTrace();

}catch(InterruptedExceptione){

//TODOAuto-generated catch block

e.printStackTrace();

}

}

/**

* FTP远程命令列表USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASVSTOR

* REST CWD STAT RMD XCUP OPTS ACCTTYPE APPE RNFR XCWD HELP XRMD STOU

* AUTH REIN STRU SMNT RNTO LIST NOOPPWD SIZE PBSZ QUIT MODE SYST ABOR

* NLST MKD XPWD MDTM PROT

*在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\n

* ftpclient.sendServer("XMKD/test/bb\r\n"); //执行服务器上的FTP命令

* ftpclient.readServerResponse一定要在sendServer后调用

* nameList("/test")获取指目录下的文件列表XMKD建立目录,当目录存在的情况下再次创建目录时报错XRMD删除目录

* DELE删除文件

*/

}

staticStringworkPath=null;

publicstaticStringgetPropertiesValueByKey(StringfileName,Stringkey){

Propertiesp=newProperties();

Stringvalue="";

try{

InputStreamin=newBufferedInputStream(newFileInputStream(fileName));

p.load(in);

value=p.getProperty(key);

}catch(Exceptione){

e.printStackTrace();

return"";

}

returnvalue;

}

}

Apache库的方法

需要依赖commons-net-3.1.jar库可以apache官方下载

importjava.io.BufferedInputStream;

importjava.io.BufferedReader;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.FileOutputStream;

importjava.io.FileReader;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importjava.sql.CallableStatement;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.util.Properties;

importjava.util.StringTokenizer;

importorg.apache.commons.lang.StringUtils;

importorg.apache.commons.net.ftp.FTP;

importorg.apache.commons.net.ftp.FTPClient;

importorg.apache.commons.net.ftp.FTPFile;

importorg.apache.log4j.Logger;

/*

* Copyright (C) 2011-2014 dshine.com

* All rights reserved.

* ShangHai Dshine -http://www.dshine.com

*/

/**

*@authorWiker Yong Email:

*@date2014-8-19下午2:00:58

*@version1.0-SNAPSHOT

*/

publicclassApacheFtpClient{

privateStringip="";

privateStringusername="";

privateStringpassword="";

privateintport=-1;

privateStringpath="";

FTPClientftpClient=null;

OutputStreamos=null;

FileInputStreamis=null;

staticStringcurFolder=System.getProperty("user.dir");

privatefinalstaticLoggerlog=Logger.getLogger(ApacheFtpClient.class);

// LogInfologinfo = new LogInfo();

publicApacheFtpClient(StringserverIP,Stringusername,Stringpassword){

this.ip=serverIP;

this.username=username;

this.password=password;

}

publicApacheFtpClient(StringserverIP,intport,Stringusername,Stringpassword){

this.ip=serverIP;

this.username=username;

this.password=password;

this.port=port;

}

publicvoidsetPath(Stringpath)

throwsIOException{

if(ftpClient==null){

this.path=path;

}else{

ftpClient.cwd(path);

}

}

/**

*连接ftp服务器

*

*@throwsIOException

*/

publicbooleanconnectServer(){

if(ftpClient!=null){

returntrue;

}

ftpClient=newFTPClient();

try{

if(this.port!=-1){

ftpClient.connect(this.ip,this.port);

}else{

ftpClient.connect(this.ip);

}

ftpClient.setControlEncoding("UTF-8");

ftpClient.login(this.username,this.password);

if(this.path.length()!=0){

ftpClient.cwd(this.path);//

path是ftp服务下主目录的子目录

}

//ftpClient.binary();//用2进制上传、下载

ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

log.info("FTP已登录到\""+ftpClient.pwd()+"\"目录");

// loginfo.appendLog("FTP已登录到\"" + ftpClient.pwd() + "\"目录");

returntrue;

}catch(IOExceptione){

log.error(e.getMessage(),e);

returnfalse;

}

}

/**

*断开与ftp服务器连接

*

*@throwsIOException

*/

publicbooleancloseServer(){

try{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

if(ftpClient!=null){

ftpClient.disconnect();

}

log.info("已从服务器断开");

// loginfo.appendLog("已从服务器断开");

returntrue;

}catch(IOExceptione){

e.printStackTrace();

returnfalse;

}

}

/**

*检查文件夹在当前目录下是否存在

*

*@paramdir

*@return

*/

publicbooleanisDirExist(Stringdir){

Stringpwd="";

try{

//pwd = ftpClient.pwd();

ftpClient.cwd(dir);

ftpClient.cwd(pwd);

}catch(Exceptione){

returnfalse;

}

returntrue;

}

//    public boolean rename(String str1, Stringstr2)

//            throws IOException {

//        String file1 = "";

//        String file2 = "";

//        String folder1 = "";

//        String folder2 = "";

//        file1 =str1.substring(str1.lastIndexOf("/") + 1, str1.length());

//        file2 =str2.substring(str2.lastIndexOf("/") + 1, str2.length());

//        folder1 = str1.substring(0,str1.lastIndexOf("/") + 1);

//        folder2 = str2.substring(0, str2.lastIndexOf("/")+ 1);

//        if (!isDirExist(folder2)) {

//            createDir(folder2);

//        }

//        ftpClient.rename(str1, str2);

//        List l = this.getFileList(folder2);

//        for (int i = 0; i < l.size();i++) {

//            if(l.get(i).toString().indexOf(file2) > 0) {

//                return true;

//            }

//        }

//        return false;

//    }

publicvoidsendCMD(Stringcmd)

throwsIOException{

ftpClient.sendCommand(cmd);

log.info(cmd.replaceAll("\r\n","\\\\r\\\\n"));

intreply=ftpClient.getReply();

log.info("Server Response:"+reply);

// log.info(reply);

}

/**

*在当前目录下创建文件夹

*

*@paramdir

*@return

*@throwsException

*/

privatebooleancreateDir(Stringdir){

try{

ftpClient.setFileTransferMode(FTP.ASCII_FILE_TYPE);

StringTokenizers=newStringTokenizer(dir,"/");//

sign

s.countTokens();

StringpathName="";//ftpClient.pwd();

while(s.hasMoreElements()){

pathName=pathName+"/"+(String)s.nextElement();

if(this.isDirExist(pathName)){

continue;

}

try{

ftpClient.sendCommand("MKD

"+pathName+"\r\n");

}catch(Exceptione){

e=null;

returnfalse;

}

ftpClient.getReply();

}

ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

returntrue;

}catch(IOExceptione1){

e1.printStackTrace();

returnfalse;

}

}

/**

* ftp上传如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

*@paramfilename

*要上传的文件(或文件夹)名

*@return

*@throwsException

*/

/*publicboolean upload(String filename) {

String newname = "";

if (filename.indexOf("/")> -1) {

newname =filename.substring(filename.lastIndexOf("/") + 1);

} else {

newname = filename;

}

return upload(filename, newname);

}*/

/**

* ftp上传如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

*@paramfileName

*要上传的文件(或文件夹)名

*@paramnewName

*服务器段要生成的文件(或文件夹)名

*@return

*/

/*publicboolean upload(String fileName, String newName) {

try {

String savefilename = newString(fileName.getBytes("ISO-8859-1"), "GBK");

File file_in = new File(savefilename);//打开本地待长传的文件

if (!file_in.exists()) {

throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");

}

if (file_in.isDirectory()) {

upload(file_in.getPath(),newName, ftpClient.pwd());

} else {

uploadFile(file_in.getPath(),newName);

}

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

return true;

} catch (Exception e) {

e.printStackTrace();

System.err.println("Exceptione in

Ftp upload(): " + e.toString());

return false;

} finally {

try {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}*/

/**

*真正用于上传的方法

*

*@paramfileName

*@paramnewName

*@parampath

*@throwsException

*/

/*privatevoid upload(String fileName, String newName, String path)

throws Exception {

String savefilename = newString(fileName.getBytes("ISO-8859-1"), "GBK");

File file_in = new File(savefilename);//打开本地待长传的文件

if (!file_in.exists()) {

throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");

}

if (file_in.isDirectory()) {

if (!isDirExist(newName)) {

createDir(newName);

}

ftpClient.cwd(newName);

File sourceFile[] =file_in.listFiles();

for (int i = 0; i

if (!sourceFile[i].exists()) {

continue;

}

if(sourceFile[i].isDirectory()) {

this.upload(sourceFile[i].getPath(), sourceFile[i].getName(), path +"/"

+ newName);

} else {

this.uploadFile(sourceFile[i].getPath(), sourceFile[i].getName());

}

}

} else {

uploadFile(file_in.getPath(),newName);

}

ftpClient.cwd(path);

}*/

/**

* upload上传文件

*

*@paramfilename

*要上传的文件名

*@paramnewname

*上传后的新文件名

*@return-1文件不存在>=0

成功上传,返回文件的大小

*@throwsException

*/

/*publiclong uploadFile(String filename, String

newname)

throws Exception {

long result = 0;

TelnetOutputStream os = null;

FileInputStream is = null;

try {

java.io.File file_in = newjava.io.File(filename);

if (!file_in.exists()) {

return -1;

}

os = ftpClient.put(newname);

result = file_in.length();

is = new FileInputStream(file_in);

byte[] bytes = new byte[1024];

int c;

while ((c = is.read(bytes)) != -1){

os.write(bytes, 0, c);

}

} finally {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

}

return result;

}*/

/**

*从ftp下载文件到本地

*

*@paramfilename

*服务器上的文件名

*@paramnewfilename

*本地生成的文件名

*@return

*@throwsException

*/

publicbooleandownloadFile(Stringfilename,Stringnewfilename){

longresult=0;

InputStreamis=null;

FileOutputStreamos=null;

try{

filename=newString(filename.getBytes("UTF-8"),"ISO-8859-1");

is=ftpClient.retrieveFileStream(filename);

java.io.Fileoutfile=newjava.io.File(newfilename);

if(!outfile.getParentFile().exists()){

outfile.getParentFile().mkdirs();

}

log.info("Download File:"+outfile.getPath());

os=newFileOutputStream(outfile);

byte[]bytes=newbyte[1024];

intc;

while((c=is.read(bytes))!=-1){

os.write(bytes,0,c);

result=result+c;

}

returnftpClient.completePendingCommand();

}catch(IOExceptione){

log.error(e.getMessage(),e);

}finally{

try{

if(is!=null){

is.close();

}

if(os!=null){

os.close();

}

}catch(IOExceptione){

log.error(e.getMessage(),e);

}

}

returnfalse;

}

/**

*取得相对于当前连接目录的某个目录下所有文件列表

*

*@parampath

*@return

*/

/* publicList getFileList(String path) {

List list = new ArrayList();

DataInputStream dis;

try {

log.info(this.path + path);

dis = newDataInputStream(ftpClient.li.nameList(this.path + path));

String filename = "";

while ((filename = dis.readLine())!= null) {

String sfilename = newString(filename.getBytes("ISO-8859-1"), "utf-8");

list.add(sfilename);

}

} catch (IOException e) {

e.printStackTrace();

}

return list;

}*/

publicstaticvoidmain(String[]args)

throwsIOException{

workPath=ApacheFtpClient.class.getClass().getResource("/").getPath();

StringtempFolder=getPropertiesValueByKey(workPath+"/application.properties",

"download.path");

Filefile=newFile(tempFolder);

if(!file.exists()){

file.mkdir();

}

StringftpIp=getPropertiesValueByKey(workPath+"/application.properties","ftp.ip");

Stringport=getPropertiesValueByKey(workPath+"/application.properties","ftp.port");

Stringuser=getPropertiesValueByKey(workPath+"/application.properties","ftp.user");

Stringpassword=getPropertiesValueByKey(workPath+"/application.properties",

"ftp.password");

Stringsleep=getPropertiesValueByKey(workPath+"/application.properties","sleep.time");

sleep=StringUtils.defaultIfEmpty(sleep,"3600");

//String[] reqPathArr ={"/add/request","/all/request"};

StringaddReqPath="/add/request";

StringallReqPath="/all/request";

//readAllReq("D:\\temp\\add\\request\\SubscribeInfo000329522012082014060510824.req");

while(true){

{

ApacheFtpClientftp=newApacheFtpClient(ftpIp,Integer.valueOf(port),user,password);

ftp.setPath(addReqPath);

ftp.connectServer();

// boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");

// log.info(result ? "上传成功!" : "上传失败!");

FTPFile[]list=ftp.ftpClient.listFiles();

for(FTPFileftpfile:list){

if(ftpfile.isFile()){

StringlocalPath=tempFolder+addReqPath+"/"

+ftpfile.getName();

ftp.downloadFile(

ftpfile.getName(),localPath);

StringdelfileName=newString(ftpfile.getName().getBytes("UTF-8"),"ISO-8859-1");

log.info("DELEfile:"+addReqPath+"/"+ftpfile.getName());

readAddReq(localPath);

ftp.ftpClient.deleteFile(addReqPath+"/"+delfileName);

}

//log.info(ftpfile.getName());

}

ftp.closeServer();

}

{

ApacheFtpClientftp=newApacheFtpClient(ftpIp,Integer.valueOf(port),user,password);

ftp.setPath(allReqPath);

ftp.connectServer();

// boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");

// log.info(result ? "上传成功!" : "上传失败!");

FTPFile[]list=ftp.ftpClient.listFiles();

for(FTPFileftpfile:list){

if(ftpfile.isFile()){

StringlocalPath=tempFolder+addReqPath+"/"

+ftpfile.getName();

ftp.downloadFile(

ftpfile.getName(),localPath);

StringdelfileName=newString(ftpfile.getName().getBytes("UTF-8"),"ISO-8859-1");

log.info("DELEfile:"+allReqPath+"/"+ftpfile.getName());

readAllReq(localPath);

ftp.ftpClient.deleteFile(allReqPath+"/"+delfileName);

}

//log.info(ftpfile.getName());

}

ftp.closeServer();

}

try{

log.info("休眠"+sleep

+"秒");

Thread.sleep(Integer.valueOf(sleep)*1000);

}catch(NumberFormatExceptione){

log.error(e.getMessage(),e);

}catch(InterruptedExceptione){

log.error(e.getMessage(),e);

}

}

/**

* FTP远程命令列表USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASVSTOR

* REST CWD STAT RMD XCUP OPTS ACCTTYPE APPE RNFR XCWD HELP XRMD STOU

* AUTH REIN STRU SMNT RNTO LIST NOOPPWD SIZE PBSZ QUIT MODE SYST ABOR

* NLST MKD XPWD MDTM PROT

*在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\n

* ftpclient.sendServer("XMKD/test/bb\r\n"); //执行服务器上的FTP命令

* ftpclient.readServerResponse一定要在sendServer后调用

* nameList("/test")获取指目录下的文件列表XMKD建立目录,当目录存在的情况下再次创建目录时报错XRMD删除目录

* DELE删除文件

*/

}

publicstaticConnectiongetConnection(){

inttime=0;

Connectionconn=null;

do{

try{

Class.forName(getPropertiesValueByKey(workPath

+"/application.properties","className"));

conn=DriverManager.getConnection(

getPropertiesValueByKey(workPath

+"/application.properties","connUrl"),

getPropertiesValueByKey(workPath

+"/application.properties","userName"),

getPropertiesValueByKey(workPath

+"/application.properties","password"));

log.debug("数据库连接成功");

break;

}catch(Exceptione){

log.error("数据库连接失败",e);

time++;

try{

Thread.sleep(3000);

}catch(InterruptedExceptione1){

e1.printStackTrace();

}

}

}while(time<3);

returnconn;

}

publicstaticvoidreadAllReq(Stringpath){

log.info("Read all request file:"+path);

BufferedReaderreader=null;

Connectioncon=getConnection();//数据连接

try{

log.info("Read file:"+path);

Filefile=newFile(path);

reader=newBufferedReader(newFileReader(file));

intline=1;

StringtempString=null;

while((tempString=reader.readLine())!=null){

//System.out.println("line"+line+":"+tempString.split("\t").length);

String[]tempArr=tempString.split("\t");

if(tempArr.length!=15){

log.warn("Line length error!line "+line+":"+tempString);

continue;

}

String[]param=tempArr;

Stringsql="{call[test].[dbo].[test](?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";

CallableStatementcall=con.prepareCall(sql);

call.setString(1,param[0]);

call.setString(2,param[1]);

call.setString(3,param[2]);

call.setString(4,param[3]);

call.setString(5,param[4]);

call.setString(6,param[5]);

call.setString(7,param[6]);

call.setString(8,param[7]);

call.setString(9,param[8]);

call.setString(10,param[9]);

call.setString(11,param[10]);

call.setString(12,param[11]);

call.setString(13,param[12]);

call.setString(14,param[13]);

call.setString(15,param[14]);

call.execute();

line++;

}

reader.close();

}catch(Exceptione){

log.error(e.getMessage(),e);

}finally{

if(reader!=null){

try{

reader.close();

}catch(IOExceptione1){

}

}

try{

if(con!=null)

con.close();

}catch(SQLExceptione){

}

}

}

publicstaticvoidreadAddReq(Stringpath){

BufferedReaderreader=null;

log.info("Read add request file:"+path);

Connectioncon=getConnection();//数据连接

try{

Filefile=newFile(path);

reader=newBufferedReader(newFileReader(file));

intline=1;

StringtempString=null;

while((tempString=reader.readLine())!=null){

//System.out.println("line"+line+":"+tempString.split("\t").length);

String[]tempArr=tempString.split("\t");

if(tempArr.length!=15){

log.warn("Line length error!line "+line+":"+tempString);

continue;

}

String[]param=tempArr;

Stringsql="{call[AndroidPlatform].[dbo].[pJTgdlt_ftp_add](?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";

CallableStatementcall=con.prepareCall(sql);

call.setString(1,param[0]);

call.setString(2,param[1]);

call.setString(3,param[2]);

call.setString(4,param[3]);

call.setString(5,param[4]);

call.setString(6,param[5]);

call.setString(7,param[6]);

call.setString(8,param[7]);

call.setString(9,param[8]);

call.setString(10,param[9]);

call.setString(11,param[10]);

call.setString(12,param[11]);

call.setString(13,param[12]);

call.setString(14,param[13]);

call.setString(15,param[14]);

call.execute();

line++;

}

reader.close();

}catch(Exceptione){

log.error(e.getMessage(),e);

}finally{

if(reader!=null){

try{

reader.close();

}catch(IOExceptione1){

}

}

}

}

staticStringworkPath=null;

publicstaticStringgetPropertiesValueByKey(StringfileName,Stringkey){

Propertiesp=newProperties();

Stringvalue="";

try{

InputStreamin=newBufferedInputStream(newFileInputStream(fileName));

p.load(in);

value=p.getProperty(key);

}catch(Exceptione){

e.printStackTrace();

return"";

}

returnvalue;

}

}

原文:http://blog.csdn.net/wiker_yong/article/details/39118719

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_35677144/article/details/115041273

智能推荐

钢筋(螺纹钢)检测计数数据集_钢筋网检测数据集-程序员宅基地

文章浏览阅读379次,点赞9次,收藏7次。人工智能深度学习钢筋(螺纹钢)检测计数数据集,近2000张图像,人工打标,标注完整。_钢筋网检测数据集

Glide-----一个新的android图片处理开源项目_安卓图片处理开源-程序员宅基地

文章浏览阅读1.7k次。英文原文 Introduction to Glide, Image Loader Library for Android, recommended by Google首发地址 http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0327/2650.html在泰国举行的谷歌开发者论坛上,谷歌为我们介绍了一个名叫 Glide 的图_安卓图片处理开源

org.springframework.validation.BindException:_org.springframework.validation.beanpropertybinding-程序员宅基地

文章浏览阅读1.5k次。org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errorsField error in object 'supply' on field 'createtime1': rejected value [2018-09-16]; cod..._org.springframework.validation.beanpropertybindingresult: 1 errors

【C++初阶】一、C++入门基础(详细总结)-程序员宅基地

文章浏览阅读1.5w次,点赞97次,收藏448次。C++是基于C语言而产生的,它既可以进行C语言的过程化程序设计,又可以进行以抽象数据类型为特点的基于对象的程序设计,还可以进行面向对象的程序设计。定义命名空间,需要使用到namespace关键字,后面跟命名空间的名字(随自己定义),然后接一对{}即可,{}中即为命名空间的成员。注意:一个命名空间就定义了一个新的作用域,命名空间中的所有内容都局限于该命名空间中。_c++入门

嵌入式测试-程序员宅基地

文章浏览阅读1.5w次,点赞14次,收藏126次。一、嵌入式软件测试的方法  嵌入式软件测试分为4个阶段,即模块测试、集成测试、系统测试、硬件/软件集成测试。前3个阶段适用于任何软件的测试,硬件/软件集成测试阶段是嵌入式软件所特有的,目的是验证嵌入式软件与其所控制的硬件设备能否正确地交互。  在嵌入式软件测试中,常采取折中的方式。基于目标的测试消耗较多的经费和时间,而基于宿主的测试代价较小,但毕竟是在模拟环境中进行的。目前的趋势是把更多的测试转移到宿主环境中进行,但是,目标环境的复杂性和独特性不可能完全模拟。  在两个环境中可以出现不同的软件缺_嵌入式测试

注册登陆业务逻辑实现_利用面向对象思路,设计和完成“手机号注册校验”业务逻辑。如果涉及db存储逻辑,你-程序员宅基地

文章浏览阅读4.1k次,点赞4次,收藏18次。注册前端 ajax发起请求 -&amp;gt;调用注册接口后端 设置路由 &amp;lt;—&amp;gt; controller层后端 注册接口的逻辑实现 a. database连接数据库 b. model层负责数据库增删改查 c. controller层导入模块-&amp;gt;model d. model-&amp;gt;查询用户名是否存在 f. 有/提..._利用面向对象思路,设计和完成“手机号注册校验”业务逻辑。如果涉及db存储逻辑,你

随便推点

单目图像深度估计 - 无监督篇:Left-Right Consistency & Ego Motion-程序员宅基地

文章浏览阅读3k次。单目图像深度估计 - 6. 无监督篇:Left-Right Consistency & Ego Motion近几年有关单目图像深度识别的算法以CNN为主流,更细的说是以无监督的同时对深度、计算机角度、光流等同时计算的端到端深度网络为主流。所谓无监督其实是指在训练过程中不需要输入真实的深度值,这样做有一个好处就是目前能够测量到深度信息的传感器还不够精确,因此由不够精确的label训练出的model得到的预测结果必然不会特别令人满意;所谓同时计算呢,在我理解是指在训练过程中,用一个能够表征时间序列_图像深度估计

QT Layout中增删widget与切换界面_qlayout removewidget会改变父窗口吗-程序员宅基地

文章浏览阅读1.1w次,点赞7次,收藏25次。背景:以QGroupBox为father widget,用VBoxLayout的布局排版多个checkBox。接下来解决三个问题: (1)在VBoxLayout中增添checkBox并显示 (2)从VBoxLayout中删除checkBox (3)切换groupBox中的界面在QGroupBox中以VBoxLayout添加子widget (checkBox)失败的案例:_qlayout removewidget会改变父窗口吗

Web前端开发(七)--正则表达式,jQ选择器,操作元素,尺寸_前端正则表达式 长宽 高 取规则字符-程序员宅基地

文章浏览阅读303次。一、正则表达式使用单个字符,区间所符合某个规则的字符串。声明正则对象1.new RegExp();使用这个方法时需要注意,如果有转义字符,需要进行两次转义。2.var reg=/…/;内置方法1.text()返回匹配结果,成功为true,不成功为false。2.exec()匹配成功返回时数组,不成功返回null。转义字符\w 单个的数字字母下划..._前端正则表达式 长宽 高 取规则字符

华为硬件笔试 通用器件知识2_华为硬件笔试题(最新版)-程序员宅基地

文章浏览阅读2.7k次。《华为硬件笔试题(最新版)》由会员分享,可在线阅读,更多相关《华为硬件笔试题(最新版)(3页珍藏版)》请在人人文库网上搜索。1、一 选择 13 个题目,没有全部抄下来,涉及的课程有电路,模拟电路,数字电路,信号与系统,微机原理 ,网络,数字信号处理 有关于 1.微分电路 2.CISC,RISC 3.数据链路层 二 填空 10 个题目,没有全部抄下来,涉及的课程有电路,模拟电路,数字电路,信号与系统..._华为器件机考

jieba结巴分词--关键词抽取(核心词抽取)_jieba分词提取关键词-程序员宅基地

文章浏览阅读5.3k次,点赞3次,收藏23次。转自:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明。谢谢!1 简介关键词抽取就是从文本里面把跟这篇文档意义最相关的一些词抽取出来。这个可以追溯到文献检索初期,当时还不支持全文搜索的时候,关键词就可以作为搜索这篇论文的词语。因此,目前依然可以在论文中看到关键词这一项。除了这些,关键词还可以在文本聚类、分类、自动摘要等领域中有着重_jieba分词提取关键词

source insight怎样恢复默认界面设置!_sourceinsight 窗口这么回复默认-程序员宅基地

文章浏览阅读6.2w次,点赞13次,收藏29次。郁闷,文件搜索的窗口让我弄没了,界面被我弄乱了,。最终的想法恢复一下默认就好了。解决方案有一下几种:1)快捷键:CTRL+O2)视图选择,项目窗口打勾就行了3)这个配置文件保存在 我的文档里面Source Insight\Settings文件夹里面关闭SI,把settings里边的配置文件删掉,重新打开SI,就恢复默认的全部设置了4)关闭source insig_sourceinsight 窗口这么回复默认

推荐文章

热门文章

相关标签