>  기사  >  Java  >  FTP 업로드 예제 코드

FTP 업로드 예제 코드

PHP中文网
PHP中文网원래의
2017-06-20 09:51:251377검색

/**
*FTP 업로드 도구 수업
*
*/
public class FtpUtil {
static Logger logger = Logger.getLogger(FtpUtil.class.getName());
   private String ip;
   private String 사용자 이름;
   private String 비밀번호;
   private int port = -1;
   private String path;
   private OutputStream os = null;
   private FileInputStream is = null;
private FTPClient ftpClient;
public FTPClient getftpClient() { return ftpClient; }
public void setftpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
public FtpUtil(){

}
public FtpUtil(String serverIP, String 사용자 이름, String 비밀번호) {
 this.ip = serverIP;
this.username = 사용자 이름;
 this.password = 비밀번호;
}

public FtpUtil(String serverIP, int port, String 사용자 이름, String 비밀번호) {
 this.ip = serverIP;
 this.username = 사용자 이름;
 this. 비밀번호 = 비밀번호;
 this.port = 포트;
 this.ftpClient= new FTPClient();
}
/**
*
* @return 서버 연결 여부
*/
public boolean ftpLogin() {  
boolean isLogin = false;  
FTPClientConfig ftpClientConfig = new FTPClientConfig();  
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());  
this.ftpClient.setControlEncoding("GBK");  
this.ftpClient.configure(ftpClientConfig);  
시도 {    
if (this.port > 0) {    
this.ftpClient.connect(this.ip, this.port);    
}else {    
this.ftpClient.connect(this.ip);    
}  
int reply = this.ftpClient.getReplyCode();    
if (!FTPReply.isPositiveCompletion(reply)) {    
this.ftpClient.disconnect();
logger.info("登录FTP服务失败!");  
반환 isLogin;    
}    
if(this.ftpClient.login(this.username, this.password)){
this.ftpClient.enterLocalPassiveMode(); // 设置传输协议        
this.ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
logger.info(this.username + "成功登陆FTP服务器");  
isLogin = 사실;
}else{
logger.info(this.username + "登录FTP服务失败!");
}
}catch (예외 e) {    
e.printStackTrace();  
logger.error( e.getMessage());  
}  
this.ftpClient.setBufferSize(1024 * 2);  
this.ftpClient.setDataTimeout(30 * 1000);  
반환 isLogin;  
}
/**
* @Exit 서버 링크 닫기
*/  
public void ftpLogOut() {  
if (null != this.ftpClient && this.ftpClient.isConnected()) {    
try {    
boolean reuslt = this.ftpClient.logout( );// 退takeFTP服务器      
if (reuslt) {  
logger.info("成功退 Out服务器");  
}    
}catch (IOException e) {    
e.printStackTrace();  
logger.warn("FTP服务器异常!" + e.getMessage());    
}마지막으로 {    
시도 {      
this.ftpClient.disconnect();
}catch (IOException e) {      
e.printStackTrace();
logger.error("关闭FTP服务器的连接异常!");    
}    
}  
}  
}
/**
* Ftp 파일 업로드
* @param localFile 로컬 파일
* @param romotUpLoadePath 업로드 서버 경로
*/  
public boolean uploadFile(File localFile, String romotUpLoadePath) {  
BufferedInputStream inStream = null;  
부울 성공 = false;  
시도 {    
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);
inStream = new BufferedInputStream(new FileInputStream(localFile));  
성공 = this.ftpClient.storeFile(localFile.getName(), inStream);    
if (success == true) {  
System.out.println(localFile.getName() + "上传成功");///
return 성공;    
}  
}catch (FileNotFoundException e) {    
e.printStackTrace();  
}catch (IOException e) {    
e.printStackTrace();  
}마지막으로 {    
if (inStream != null) {    
try {      
inStream.close();    
}catch (IOException e) {      
e.printStackTrace();    
}    
}  
}  
반환 성공;  
}  

/**업로드 폴더
* @param localDirectory 로컬 폴더
* @param remoteDirectoryPath 원격 경로
*/  
public boolean uploadDirectory(String localDirectory,String RemoteDirectoryPath) {  
File src = new File(localDirectory);  
System.out.println(src.getName());
try {    
원격디렉토리패스 = 원격디렉토리패스 + src.getName() + "/";    
부울 makeDirFlag = ftpClient.makeDirectory(remoteDirectoryPath);    
System.out.println("localDirectory : " + localDirectory);    
System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);    
System.out.println("src.getName() : " + src.getName());    
System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);    
System.out.println("makeDirFlag : " + makeDirFlag);  
// ftpClient.listDirectories();  
}catch (IOException e) {    
e.printStackTrace();
}  
File[] allFile = src.listFiles();
if(allFile.length==0||allFile.length>0){
for (int currentFile = 0;currentFile < allFile.length;currentFile++) {    
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();    
uploadFile(새 파일(srcName), remoteDirectoryPath);    
}
}  
for (int currentFile = 0;currentFile < allFile.length;currentFile++) {    
if (allFile[currentFile].isDirectory()) {
uploadDirectory(allFile[currentFile].getPath().toString() ,  //递归      
remoteDirectoryPath);    
}  
}  
}
/*for (int currentFile = 0;currentFile < allFile.length;currentFile++) {    
if (!allFile[currentFile].isDirectory()) {    
String srcName = allFile[currentFile].getPath ().toString();    
uploadFile(새 파일(srcName), remoteDirectoryPath);    
}
}  
for (int currentFile = 0;currentFile < allFile.length;currentFile++) {    
if (allFile[currentFile].isDirectory()) {
uploadDirectory(allFile[currentFile].getPath().toString() ,  //递归      
remoteDirectoryPath);    
}  
}   */
true를 반환합니다.  
}  

위 내용은 FTP 업로드 예제 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.