이 기사는 참조를 위해 Java FTP 파일을 업로드하고 다운로드하는 두 가지 방법과 공유했습니다. 특정 내용은 다음과 같습니다
첫 번째 방법 :
package com.cloudpower.util; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import sun.net.telnetInputStream; import sun.telnetoutputStream; import sun.ftp.ftpcclient;/** java ' @title : ftp.java* @author : zhou lingbin*/public class ftp {/*** 로컬 파일 이름*/private string localfilename; / *** 원격 파일 이름*/ 개인 문자열 remoteFileName; / *** ftp 클라이언트*/ private ftpclient ftpclient; /** * Server connection* @param ip Server IP * @param port Server port* @param user user name* @param password Password* @param path Server path* @author Zhou Lingbin* @date 2012-7-11 */ public void connectServer(String ip, int port, String user, String password, String path) { try { /* *******Two methods to connect to the server*******/ //The first method // ftpclient = new ftpclient (); // ftpclient.openserver (ip, port); // 두 번째 방법 ftpclient = new ftpclient (IP); ftpclient.login (사용자, 암호); // 이진 전송으로 설정 ftpclient.binary (); System.out.println ( "로그인 성공!"); if (path.length ()! = 0) {// 원격 시스템의 디렉토리를 원격 시스템의 디렉토리를 매개 변수 path ftpclient.cd (path)로 지정된 디렉토리로 전환합니다. } ftpclient.binary (); } catch (ioexception ex) {ex.printstacktrace (); 새로운 runtimeexception (예)를 던지십시오. }} / *** 연결을 닫습니다* @Author Zhou Lingbin* @date 2012-7-11* / public void closeConnect () {try {ftpclient.closeserver (); System.out.println ( "Disternect Success"); } catch (ioException ex) {System.out.println ( "연결이 끊지 않음"); ex.printstacktrace (); 새로운 runtimeexception (예)를 던지십시오. }} / *** 파일 업로드* @param localfile local file* @param remotefile 원격 파일* @author zhou lingbin* @date 2012-7-11* / public void upload (문자열 로컬 파일, 문자열 원격 파일) {this.localfilename = localfile; this.remotefilename = RemoteFile; telnetoutputStream os = null; FileInputStream은 = null; 시도 {// 원격 파일을 출력 스트림에 추가합니다 os = ftpclient.put (this.remotefilename); // 로컬 파일의 입력 스트림을 가져옵니다. 파일 파일 _in = 새 파일 (this.localfilename); is = new FileInputStream (file_in); // 버퍼 바이트 생성 [] bytes = new Byte [1024]; int c; while ((c = is.read (bytes))! = -1) {os.write (bytes, 0, c); } system.out.println ( "업로드 성공"); } catch (ioException ex) {System.out.println ( "업로드되지 않음"); ex.printstacktrace (); 새로운 runtimeexception (예)를 던지십시오. } 마침내 {try {if (is! = null) {is.close (); }} catch (ioexception e) {e.printstacktrace (); } 마침내 {try {if (os! = null) {os.close (); }} catch (ioexception e) {e.printstacktrace (); }}}} / ** * 파일 다운로드 * @param remotefile 원격 파일 경로 (서버 측) * @param localfile local file path (client) * @author zhou lingbin * @date 2012-7-11 * / public void download (String remoteFile, String localFile) {TelnetInputStream is = null; fileoutputStream os = null; {// 원격 시스템에서 파일 이름을 가져 와서 TelnetInputStream을 사용하여 파일을 로컬 영역으로 전송합니다. is = ftpclient.get (remotefile); file_in = 새 파일 (localfile); os = new FileOutputStream (file_in); 바이트 [] 바이트 = 새로운 바이트 [1024]; int c; while ((c = is.read (bytes))! = -1) {os.write (bytes, 0, c); } system.out.println ( "다운로드 성공"); } catch (ioException ex) {System.out.println ( "다운로드되지 않음"); ex.printstacktrace (); 새로운 runtimeexception (예)를 던지십시오. } 마침내 {try {if (is! = null) {is.close (); }} catch (ioexception e) {e.printstacktrace (); } 마침내 {try {if (os! = null) {os.close (); }} catch (ioexception e) {e.printstacktrace (); }}}} public static void main (String agrs []) {String filepath [] = { "/temp/aa.txt", "/temp/regist.log"}; 문자열 localFilePath [] = { "c : //tmp//1.txt", "c : //tmp//2.log"}; ftp fu = 새로운 ftp (); /** 기본 포트 번호, 사용자 이름, 비밀번호 및 루트 디렉토리를 사용하여 FTP 서버*/fu.connectServer ( "127.0.0.1", 22, "익명", "IEUSER@", "/temp")에 연결하십시오. // (int i = 0; i <filepath.length; i ++)에 대한 다운로드 {fu.download (filepath [i], localfilepath [i]); } string localfile = "e : //number.txt"; 문자열 remotefile = "/temp/haha.txt"; // fu.upload (localfile, remotefile)를 업로드합니다. fu.closeconnect (); }}
이 방법에 대해 할 말이 없으며, 상대적으로 간단하며 중국어가 달린 코드에 문제가 없습니다. 결함이 있고 큰 파일을 작동 할 수없는 것 같습니다. 관심있는 친구들은 그것을 시도 할 수 있습니다.
두 번째 방법 :
공개 클래스 ftpapche {private static ftpclient ftpclient = new ftpclient (); 개인 정적 문자열 인코딩 = System.GetProperty ( "file.encoding"); /** * 설명 : FTP 서버 * @version1.0 * @param url * ftp 서버 호스트 이름 * @param port * ftp server port * @param username * ftp login 계정 * @param password * ftp login password * @param path * ftp 서버를 저장하는 경우, 루트 이름 * @param filetame "/" * @param path * @param path * ftp 서버를 저장합니다. ftp server * @param 입력 * 로컬 파일 입력 스트림 * @return true가 성공적으로 반환합니다. {int reply; // 기본 포트가 사용되면 FTP 서버 FTPClient.connect (url)에 직접 연결할 수 있습니다. // ftp.connect (url, port); // ftp server에 연결 // ftpclient.login (username, password)에 로그인; ftpclient.setcontrolencoding (인코딩); // 연결이 성공적인지 확인 = ftpclient.getReplyCode (); if (! ftpReply.ispositiveCompletion (reply)) {System.out.println ( "연결 실패"); ftpclient.disconnect (); 반환 결과; } // 지정된 디렉토리로 작업 디렉토리를 전송 부울 변경 = ftpclient.changeworkingDirectory (PATH); ftpclient.setfiletype (ftp.binary_file_type); if (change) {result = ftpclient.storefile (new String (filename.getBytes (인코딩), "ISO-8859-1"), 입력); if (result) {system.out.println ( "성공적으로 업로드!"); }} input.close (); ftpclient.logout (); } catch (ioexception e) {e.printstacktrace (); } 마지막으로 {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioexception ioe) {}}} return result; }/*** 로컬 파일을 ftp 서버에 업로드*/public void testuploadfromdisk () {try {fileInputStream in = new FileInputStream (새 파일 ( "e : /number.txt")); 부울 플래그 = uploadfile ( "127.0.0.1", 21, "zlb", "123", "/", "haha.txt", in); System.out.println (플래그); } catch (filenotfoundException e) {e.printstacktrace (); }} /** * 설명 : ftp 서버에서 파일 다운로드 * * @version1.0 * @param url * ftp server hostname * @param port * ftp server port * @param username * ftp 로그인 계정 * @param password * ftp 로그인 * @param remotepath * @param server * @param name * @param name on the Piple wor saver on apparam path * @param remotepath * 다운로드 후 로컬에 * @return */ public static boolean downfile (문자열 URL, int port, 문자열 사용자 이름, 문자열 암호, 문자열 remotepath, String filename, String localPath) {boolean result = false; {int reply; ftpclient.setcontrolencoding (인코딩); / * * 중국어 파일을 업로드하고 다운로드하려면 일부 장소에서는 * 새 문자열 대신 다음 두 문장을 사용하는 것이 좋습니다 (remotepath.getBytes (인코딩), "ISO-8859-1") 트랜스 코딩. * 테스트 후 통과 할 수 없습니다. */// ftpclientConfig conf = new ftpclientConfig (ftpclientConfig.syst_nt); // conf.SetServerLanguageCode ( "ZH"); ftpclient.connect (URL, 포트); // 기본 포트가 사용되면 ftpclient.login (사용자 이름, 암호); // login // 파일 전송 유형을 Binary ftpclient.setFileType (ftpclient.binary_file_type)로 설정하여 ftpclient.login (username, password); // ftp 서버에 직접 연결할 수 있습니다. // ftp 로그인 응답 코드를 가져옵니다. 답장 = ftpclient.getReplyCode (); // 로그인이 성공했는지 확인하십시오 (! ftpReply.ispositiveCempletion (reply)) {ftpclient.disconnect (); System.err.println ( "FTP 서버가 연결을 거부했습니다."); 반환 결과; } // 지정된 디렉토리 FTPClient.ChangeWorkingDirectory로 FTP 서버 디렉토리로 전송합니다 (새 String (remotepath.getBytes (인코딩), "ISO-8859-1"); // 파일 목록 가져 오기 ftpfile [] fs = ftpclient.listfiles (); for (ftpfile ff : fs) {if (ff.getname (). equals (filename)) {file localfile = 새 파일 (localPath + "/" + ff.getName ()); outputStream은 = 새 파일 아웃 putStream (localfile); ftpclient.retrivefile (ff.getName (), is); is.close (); }} ftpclient.logout (); 결과 = true; } catch (ioexception e) {e.printstacktrace (); } 마지막으로 {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioexception ioe) {}}} return result; }/** * ftp 서버의 파일을 로컬 */public void testdownfile () {try {boolean flag = downfile ( "127.0.0.1", "zlb", "123", "/", "haha.txt", "d :/")로 다운로드하십시오. System.out.println (플래그); } catch (예외 e) {e.printstacktrace (); }} public static void main (String [] args) {ftpapche fa = new ftpapche (); fa.testdownfile (); }}
이런 식으로, 당신은 중국어가 달린 코드의 문제에주의를 기울여야합니다. 잘못 설정하면 업로드 된 파일 이름이 차량 코드 일 수 있습니다. 때로는 업로드 할 수 없습니다. 물론 예외는 없기 때문에 당신은 당신을 자극하지 않을 것입니다. 온라인에서 많은 솔루션을 찾았으며 여러 가지 의견이 있습니다. 그들 모두는 하나의 버전에서 복사되었으며, 나는 혼자서 테스트되지 않았습니다. 나는 이것을 위해 많은 고통을 겪었다. 대략 다음 두 가지 솔루션으로 나뉩니다.
1. 다음 세 문장을 추가하여 해결하십시오
ftpclient.setcontrolencoding ( "gbk");
ftpclientConfig conf = new ftpclientConfig (ftpclientConfig.syst_nt);
Conf.SetServerlanguagecode ( "ZH");
답변 : 테스트 후에는 단순히 작동하지 않으며 위의 문제는 여전히 존재합니다.
2. 위의 방법과 유사하지만이 방법이 더 신뢰할 수 있다고 생각합니다.
먼저 문장 ftpclient.setcontrolencoding ( "gbk")을 추가합니다. 그런 다음 모든 중국어를 다음과 같이 "ISO-8859-1"형식으로 변환합니다.
ftpclient.changeworkingdirectory (new String (remotepath.getBytes ( "gbk"), "iso-8859-1");
답 : 테스트 후에도 여전히 작동하지 않습니다. 내가이 방법을 말한 이유는 더 안정적입니다. 계속 읽으십시오.
먼저 트랜스 코드를 해야하는 이유에 대해 이야기 해 봅시다.
FTP 프로토콜에서 파일 이름은 ISO-8859-1로 인코딩되도록 지정되므로 디렉토리 이름 또는 파일 이름을 트랜스 코딩해야합니다.
다음 질문은이 형식으로 어떤 인코딩을 변환 해야하는지입니다. 따라서 GBK 형식을 ISO-8859-1 형식으로 변환하는 두 번째 솔루션이 있습니다. 또한, 어떤 사람들은 또한이 일을해야한다고 말합니다. 사실, 나는 그들이 이것을 말할 수있는 이유가 완전히 우연이라고 생각합니다. 실제 원칙은 FTP 프로토콜에 의해 지정된 인코딩 형식이 "ISO-8859-1"이므로 서버가 파일을 수신 할 때 형식을 변환 한 다음 자동으로 시스템의 인코딩 형식으로 자동 변환해야한다는 것입니다. 따라서 키는 형식을 지정하는 것이 아니라 FTP 서버의 인코딩 형식에 의존하는 것입니다. 따라서 FTP 시스템의 인코딩 형식이 "GBK"인 경우 두 번째 방법은 확실히 성공할 것입니다. 그러나 시스템의 인코딩 형식이 "UTF-8"인 경우에도 여전히 차량이 있습니다. 따라서 코드를 통해 시스템의 인코딩 형식 만 얻은 다음이 인코딩 형식을 통해 ISO-8859-1의 인코딩 형식으로 변환 할 수 있습니다. 획득 방법은 다음과 같습니다.
개인 정적 문자열 인코딩 = System.GetProperty ( "file.encoding");
위의 모든 코드는 스스로 테스트되었습니다. 모든 사람에게 문제를 해결할 수 있기를 바랍니다!