org. apache. comons. net. ftp 패키지 개발 FTP 클 라 이언 트, 정지점 전송, 중국어 지원
1. 업로드 와 다운 로드 를 지원 합 니 다.정지점 전송 지원
2. 진도 보고 지원
3. 중국어 디 렉 터 리 및 중국어 파일 생 성 지원.
구체 적 으로 코드 를 보십시오. 위 에 상세 한 주석 이 있 습 니 다.간략화 버 전 참조http://zhouzaibao.iteye.com/blog/342766
클래스 UploadStatus 코드 매 거 진
public enum UploadStatus {
Create_Directory_Fail, //
Create_Directory_Success, //
Upload_New_File_Success, //
Upload_New_File_Failed, //
File_Exits, //
Remote_Bigger_Local, //
Upload_From_Break_Success, //
Upload_From_Break_Failed, //
Delete_Remote_Faild; //
}
매 거 진 클래스 DownloadStatus 코드
public enum DownloadStatus {
Remote_File_Noexist, //
Local_Bigger_Remote, //
Download_From_Break_Success, //
Download_From_Break_Failed, //
Download_New_Success, //
Download_New_Failed; //
}
핵심 FTP 코드
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import open.mis.data.DownloadStatus;
import open.mis.data.UploadStatus;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* FTP
* @author BenZhou
* @version 0.1
* @version 0.2
* @version 0.3 ,
*/
public class ContinueFTP {
public FTPClient ftpClient = new FTPClient();
public ContinueFTP(){
//
this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
}
/**
* FTP
* @param hostname
* @param port
* @param username
* @param password
* @return
* @throws IOException
*/
public boolean connect(String hostname,int port,String username,String password) throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
return true;
}
}
disconnect();
return false;
}
/**
* FTP , ,
* @param remote
* @param local
* @return
* @throws IOException
*/
public DownloadStatus download(String remote,String local) throws IOException{
//
ftpClient.enterLocalPassiveMode();
//
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatus result;
//
FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length != 1){
System.out.println(" ");
return DownloadStatus.Remote_File_Noexist;
}
long lRemoteSize = files[0].getSize();
File f = new File(local);
// ,
if(f.exists()){
long localSize = f.length();
//
if(localSize >= lRemoteSize){
System.out.println(" , ");
return DownloadStatus.Local_Bigger_Remote;
}
// ,
FileOutputStream out = new FileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=localSize /step;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes,0,c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println(" :"+process);
//TODO , process
}
}
in.close();
out.close();
boolean isDo = ftpClient.completePendingCommand();
if(isDo){
result = DownloadStatus.Download_From_Break_Success;
}else {
result = DownloadStatus.Download_From_Break_Failed;
}
}else {
OutputStream out = new FileOutputStream(f);
InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=0;
long localSize = 0L;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes, 0, c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println(" :"+process);
//TODO , process
}
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if(upNewStatus){
result = DownloadStatus.Download_New_Success;
}else {
result = DownloadStatus.Download_New_Failed;
}
}
return result;
}
/**
* FTP ,
* @param local ,
* @param remote , /home/directory1/subdirectory/file.ext Linux , ,
* @return
* @throws IOException
*/
public UploadStatus upload(String local,String remote) throws IOException{
// PassiveMode
ftpClient.enterLocalPassiveMode();
//
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatus result;
//
String remoteFileName = remote;
if(remote.contains("/")){
remoteFileName = remote.substring(remote.lastIndexOf("/")+1);
// ,
if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){
return UploadStatus.Create_Directory_Fail;
}
}
//
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length == 1){
long remoteSize = files[0].getSize();
File f = new File(local);
long localSize = f.length();
if(remoteSize==localSize){
return UploadStatus.File_Exits;
}else if(remoteSize > localSize){
return UploadStatus.Remote_Bigger_Local;
}
// ,
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
// , ,
if(result == UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
return UploadStatus.Delete_Remote_Faild;
}
result = uploadFile(remoteFileName, f, ftpClient, 0);
}
}else {
result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
}
return result;
}
/**
*
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
/**
*
* @param remote
* @param ftpClient FTPClient
* @return
* @throws IOException
*/
public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){
// ,
int start=0;
int end = 0;
if(directory.startsWith("/")){
start = 1;
}else{
start = 0;
}
end = directory.indexOf("/",start);
while(true){
String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else {
System.out.println(" ");
return UploadStatus.Create_Directory_Fail;
}
}
start = end + 1;
end = directory.indexOf("/",start);
//
if(end <= start){
break;
}
}
}
return status;
}
/**
* ,
* @param remoteFile ,
* @param localFile File ,
* @param processStep
* @param ftpClient FTPClient
* @return
* @throws IOException
*/
public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{
UploadStatus status;
//
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile,"r");
OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1"));
//
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process = remoteSize /step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while((c = raf.read(bytes))!= -1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes / step != process){
process = localreadbytes / step;
System.out.println(" :" + process);
//TODO
}
}
out.flush();
raf.close();
out.close();
boolean result =ftpClient.completePendingCommand();
if(remoteSize > 0){
status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else {
status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
return status;
}
public static void main(String[] args) {
ContinueFTP myFtp = new ContinueFTP();
try {
myFtp.connect("192.168.21.181", 21, "nid", "123");
// myFtp.ftpClient.makeDirectory(new String(" ".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(new String(" ".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(new String(" ".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\\yw.flv", "/yw.flv",5));
// System.out.println(myFtp.upload("E:\\ 24.mp4","/ / / 24.mp4"));
System.out.println(myFtp.download("/ / / 24.mp4", "E:\\ 242.mp4"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println(" FTP :"+e.getMessage());
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 파일 압축 및 압축 풀기파일 의 간단 한 압축 과 압축 해 제 를 실현 하 였 다.주요 테스트 용 에는 급 하 게 쓸 수 있 는 부분 이 있 으 니 불편 한 점 이 있 으 면 아낌없이 가르쳐 주 십시오. 1. 중국어 문 제 를 해 결 했 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.