자바 ftp/sftp 구축 데이터 전달 전 과정
ftp 는 클 라 이언 트 와 서버 가 서로 파일,그림 등 데 이 터 를 전달 할 수 있 도록 파일 전송 프로 토 콜 입 니 다.편리 하고 빠르다.
sftp 는 ssh file transfer protocol 의 줄 임 말 이자 파일 전송 프로 토 콜 입 니 다.sftp 는 ftp 보다 안전 하지만 전송 효율 이 낮 습 니 다.
구축:
ftp 는 인터넷 튜 토리 얼 을 검색 할 수 있 습 니 다.많 습 니 다.
생 성 이 완료 되면 브 라 우 저 를 통 해 내용 에 접근 할 수 있 습 니 다.
sftp 는 freesshd 로 구축 합 니 다(freesshd 의 설치 경 로 는 중국어 가 있어 서 는 안 됩 니 다.그렇지 않 으 면 각종 오류 가 발생 합 니 다).이것 도 스스로 바 이 두 를 할 수 있 고 해결 방법 이 많다.
자바 코드
:
import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
public class FTPClientTest
{
private static String userName; // FTP
private static String password; // FTP
private static String ip;// FTP IP
private static int port; // FTP
//
public FTPClientTest(String userName,String password,String ip,int port){
this.userName=userName;
this.password=password;
this.ip=ip;
this.port=port;
}
public static String getUserName(){ return userName;}
public static void setUserName(String userName) {FTPClientTest.userName = userName; }
public static String getPassword() {return password;}
public static void setPassword(String password){FTPClientTest.password = password;}
public static String getIp() { return ip; }
public static void setIp(String ip){FTPClientTest.ip = ip;}
public static int getPort() {return port; }
public static void setPort(int port) {FTPClientTest.port = port;}
private static FTPClient ftpClient = null; // FTP
/**
*
* @return true ,false
*/
public boolean connectServer()
{
System.out.println(" ");
boolean flag = true;
if (ftpClient == null)
{
int reply;
try
{
System.out.println(" ");
ftpClient = new FTPClient();
String LOCAL_CHARSET = "GBK";
System.out.println(" IP ");
ftpClient.connect(ip, port);
System.out.println(" ");
ftpClient.login(userName, password);
System.out.println(" ");
reply = ftpClient.getReplyCode();
ftpClient.setDataTimeout(120000);
System.out.println(" ");
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // UTF-8 , UTF-8 , (GBK).
{
LOCAL_CHARSET = "UTF-8";
}
System.out.println(" 1");
ftpClient.setControlEncoding(LOCAL_CHARSET);
System.out.println(" ");
if (!FTPReply.isPositiveCompletion(reply))
{
ftpClient.disconnect();
System.out.println("FTP !");
flag = false;
}
}
catch (SocketException e)
{
flag = false;
e.printStackTrace();
System.out.println(" ftp " + ip + " , !");
}
catch (IOException e)
{
flag = false;
e.printStackTrace();
System.out.println(" ftp " + ip + " ,FTP !");
}
catch (Exception e)
{
flag = false;
e.printStackTrace();
// System.out.println(" ftp " + ip + " ,FTP !");
}
}
return flag;
}
/**
*
*
* @param remoteFile ,
* @param localFile ,
*
*/
public boolean uploadFile(String remoteFile1, File localFile)
{
boolean flag = false;
try
{
InputStream in = new FileInputStream(localFile);
String remote = new String(remoteFile1.getBytes("UTF-8"), "iso-8859-1");
if (ftpClient.storeFile(remote, in))
{
flag = true;
System.out.println(localFile.getAbsolutePath() + " !");
}
else
{
System.out.println(localFile.getAbsolutePath() + " !");
}
in.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
/**
*
*
* @param local ,
* @param remote ,
* @return
*/
public boolean uploadFile(String local, String remote)
{
boolean flag = true;
String remoteFileName = remote;
if (remote.contains("/"))
{
remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
// ,
if (!CreateDirecroty(remote))
{
return false;
}
}
File f = new File(local);
if (!uploadFile(remoteFileName, f))
{
flag = false;
}
return flag;
}
/**
*
*
*
* @param filename ,
* @param uploadpath FTP , / /dir1/dir2/../
* @return true ,false
* @throws IOException
*/
public ArrayList<String> uploadManyFile(String filename, String uploadpath)
{
boolean flag = true;
ArrayList<String> l = new ArrayList<String>();
StringBuffer strBuf = new StringBuffer();
int n = 0; //
int m = 0; //
try
{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpClient.changeWorkingDirectory("/");
File file = new File(filename);
File fileList[] = file.listFiles();
for (File upfile : fileList)
{
if (!upfile.isDirectory())
{
String local = upfile.getCanonicalPath().replaceAll("\\\\", "/");
String temp = upfile.getCanonicalPath();
String a = temp.replace(filename + "\\", "");
String remote = uploadpath.replaceAll("\\\\", "/") + a;
flag = uploadFile(local, remote);
ftpClient.changeWorkingDirectory("/");
}
if (!flag)
{
n++;
strBuf.append(upfile.getName() + ",");
System.out.println(" [" + upfile.getName() + "] ");
}
else
{
m++;
}
}
l.add(" " + n);
l.add(" " + m);
l.add(strBuf.toString());
}
catch (NullPointerException e)
{
e.printStackTrace();
System.out.println(" ! !" + e);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(" !" + e);
}
return l;
}
/**
*
*
* @param remoteFileName --
* @param localFileName--
* @return true ,false
*/
public boolean loadFile(String remoteFileName, String localFileName)
{
boolean flag = true;
//
BufferedOutputStream buffOut = null;
try
{
buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), buffOut);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(" !" + e);
}
finally
{
try
{
if (buffOut != null)
buffOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return flag;
}
/**
*
*/
public boolean deleteFile(String filename)
{
boolean flag = true;
try
{
flag = ftpClient.deleteFile(new String(filename.getBytes("UTF-8"), "iso-8859-1"));
if (flag)
{
System.out.println(" " + filename + " !");
}
else
{
System.out.println(" " + filename + " !");
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return flag;
}
/**
*
*/
public void deleteEmptyDirectory(String pathname)
{
try
{
ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"), "iso-8859-1"));
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/**
* Ftp
*/
public String[] listRemoteAllFiles()
{
try
{
String[] names = ftpClient.listNames();
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
return names;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
*
*/
public void closeConnect()
{
try
{
if (ftpClient != null)
{
ftpClient.logout();
ftpClient.disconnect();
ftpClient=null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* [ ] 1
*
* @param fileType--BINARY_FILE_TYPE( )、ASCII_FILE_TYPE( )
*
*/
public void setFileType(int fileType1)
{
try
{
int a = FTP.BINARY_FILE_TYPE;
if (fileType1 == 1)
{
a = FTP.ASCII_FILE_TYPE;
}
ftpClient.setFileType(a);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
*
* @param directory
*/
public boolean changeWorkingDirectory(String directory)
{
boolean flag = true;
try
{
flag = ftpClient.changeWorkingDirectory(directory);
if (flag)
{
System.out.println(" " + directory + " !");
}
else
{
System.out.println(" " + directory + " !");
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return flag;
}
/**
*
*/
public void changeToParentDirectory()
{
try
{
ftpClient.changeToParentDirectory();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/**
*
*
* @param oldFileName --
* @param newFileName --
*/
public void renameFile(String oldFileName, String newFileName)
{
try
{
System.out.println(oldFileName);
System.out.println(newFileName);
ftpClient.rename(new String(oldFileName.getBytes("UTF-8"), "iso-8859-1"), new String(newFileName.getBytes("UTF-8"), "iso-8859-1"));
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* FTP --
*
* @return ftpConfig
*/
@SuppressWarnings("unused")
private FTPClientConfig getFtpConfig()
{
FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
}
/**
* [ISO-8859-1 -> GBK]
*
* @param obj
* @return ""
*/
@SuppressWarnings("unused")
private String iso8859togbk(Object obj)
{
try
{
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
}
catch (Exception e)
{
return "";
}
}
/**
*
*
* @param dir , , \ 、/ 、: 、* 、?、 "、 <、>...
*/
public boolean makeDirectory(String dir)
{
boolean flag = true;
try
{
flag = ftpClient.makeDirectory(dir);
if (flag)
{
System.out.println(" " + dir + " !");
}
else
{
System.out.println(" " + dir + " !");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return flag;
}
/**
*
*
* @param remote : /Draw1/Point1/GUID1/a.bmp /Draw1/Point1/GUID1/ /
*
* @return
* @throws IOException
*/
public boolean CreateDirecroty(String remote)
{
boolean success = true;
try
{
String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
// ,
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory)))
{
int start = 0;
int end = 0;
if (directory.startsWith("/"))
{
start = 1;
}
else
{
start = 0;
}
end = directory.indexOf("/", start);
while (true)
{
String subDirectory;
subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
if (!changeWorkingDirectory(subDirectory))
{
if (makeDirectory(subDirectory))
{
changeWorkingDirectory(subDirectory);
}
else
{
System.out.println(" [" + subDirectory + "] ");
System.out.println(" [" + subDirectory + "] ");
success = false;
return success;
}
}
start = end + 1;
end = directory.indexOf("/", start);
//
if (end <= start)
{
break;
}
}
}
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}
}
ftp 테스트 코드 는 다음 과 같 습 니 다:
public class test {
public static void main(String[] args) {
FTPClientTest ftp=new FTPClientTest("user", "548", "168.125.256.22", 21);
boolean b=ftp.connectServer();
System.out.println(b);
System.out.println(ftp.listRemoteAllFiles());
System.out.println(ftp.uploadFile("F:/home/b.txt", "/c.txt"));
System.out.println(ftp.loadFile("/a.txt", "F:/home/b.txt"));
ftp.closeConnect();
}
}
출력 결 과 는 다음 과 같 습 니 다.성공 하 다
sftp 구축 완료 후 테스트 를 통 해 구축 과정 에 대해 자체 바 이 두 가 좋 습 니 다.
봤 어,연결 성 공 했 어;나 는 내 컴퓨터 로 시 뮬 레이 션 했다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.