이 기사에서는 Java가 파일을 FTP 서버에 업로드하는 방법에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
도구 :
package com.fz.common.util; import java.io.datainputStream; import java.io.dataOutputStream; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioexception; java.text.simpledateformat; import java.util.date; import org.apache.commons.net.ftpclient; import org.apache.commons.net.ftp.ftpreply; public class fileutil { / ** * * @date sep 26, 2011 10:17:39 am * @ -retor zhanghor zhanghor zhangh. datainputStream getInput () {datainputStream d = null; try {d = new DatainputStream (new FileInputStream ( "C : /wmc.dat")); 반환 d; } catch (filenotfoundException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); } 반환 d; } / ** * * @Date 2011 년 9 월 26 일 10:17:44 AM * @param whites * @return * @Author Zhangh * / public static boolean creatwhitemanagefile (byte [] 흰색, 문자열 파일) {dataOutputStream d; try {d = new DataOutputStream (새 FileOutputStream (file)); D.Write (Whites); d.flush (); } catch (예외 e) {// todo 자동 생성 캐치 블록 return false; // e.printstacktrace (); } true를 반환합니다. } / ** * * @date 9 월 16 일 4:39:22 pm * @param url * @param username * @param password * @param path * @param filename * @param input * @return * @author zhangh * / public url, string username, String Path, String, inputStrem in putStrem in putStrem. = 거짓; ftpclient ftp = 새로운 ftpclient (); {int reply; ftp.connect (url); // ftp.connect (url, port); // ftp 서버에 연결 // 기본 포트를 사용하는 경우 ftp.connect (url)를 사용하여 FTP 서버에 직접 연결할 수 있습니다. ftp.login (username, password); // 로그인 reply = ftp.getReplyCode (); if (! ftpReply.ispositiveCoMpletion (답장)) {ftp.disconnect (); 반환 성공; } ftp.changeworkingDirectory (Path); ftp.storefile (파일 이름, 입력); ftp.logout (); input.close (); 성공 = 참; } catch (ioexception e) {e.printstacktrace (); } 마침내 {if (ftp.isconnected ()) {try {ftp.disconnect (); } catch (ioexception ioe) {}} 반환 성공; } / ** * * 메소드 이름 : UploadFileftp * 메소드 설명 : 블랙리스트, 흑인 사용자 파일 FTP 서버 * @Param URL * @param username * @param pathip * @param path * @param filename * @param input * @param input2 * @return * boolean * 버전 1.0 * Oct 26, 2011 3:19:19:19:19:19:19:19:19:19:19:19:09: uploadfileftp (문자열 URL, 문자열 사용자 이름, 문자열 비밀번호, 문자열 경로, 문자열 파일 이름, inputStream input, inputStream input2) {날짜 날짜 = 새 날짜 (); simpledateformat formatter = 새로운 simpledateformat ( "yyyy-mm-dd hh : mm : ss"); 문자열 시간 = formatter.format (날짜); 부울 성공 = 거짓; ftpclient ftp = 새로운 ftpclient (); {int reply; ftp.connect (URL); ftp.login (username, password); // login reply = ftp.getReplyCode (); if (! ftpReply.ispositiveCoMpletion (답장)) {ftp.disconnect (); 반환 성공; } ftp.changeworkingDirectory (Path); ftp.storefile (파일 이름, 입력); ftp.storefile (filename + time, input2); ftp.logout (); input.close (); 성공 = 참; } catch (ioexception e) {e.printstacktrace (); } 마침내 {if (ftp.isconnected ()) {try {ftp.disconnect (); } catch (ioexception ioe) {}}} 반환 성공; }}구성 파일 읽기 :
package com.fz.fzbike.domain; import java.io.bufferedInputStream; import java.io.fileInputStream; import java.io.ioException; import java.io.inputStream; import java.util.properties; import org.apache.log4j.logger; import com. * ftp 서버 정보를 얻는 Bean 클래스 * * @author wuxq * */public class sysconstats {private static logger log = logger.getLogger (sysconstats.class); public static string ftpserver; // ftp 서버 IP 주소 public static string ftpusername; // ftp 서버 사용자 이름 공개 정적 문자열 ftppassword; // ftp 서버 사용자 암호 public static string enveloperesultroot; // ftp server public sysconstats (inputStream in = new bufferedinputStream)를 저장하는 경로. sysconstants.public_path.substring (0, sysconstants.public_path.length () -7) + "/bidfileconfig.properties")); 속성 proper = new Properties (); prop.load (in); sysconstats.ftpserver = prop.getProperty ( "ftpserver", "none"); sysconstats.ftpusername = prop.getProperty ( "ftpusername", "none"); sysconstats.ftppassword = prop.getProperty ( "ftppassword", "none"); sysconstats.enveloperesultroot = prop.getProperty ( "EnveloperesUltroot", "none"); log.debug ( "FTP 구성 정보 읽기 성공!"); } catch (ioexception e) {log.debug ( "FTP 구성 정보를 읽지 못했습니다!"); e.printstacktrace (); }} public static string getftpserver () {return ftpserver; } public static void setftpserver (String ftpserver) {ftpserver = ftpserver; } public static string getftpusername () {return ftpusername; } public static void setftpusername (String ftpusername) {ftpusername = ftpusername; } public static string getftppassword () {return ftppassword; } public static void setftppassword (String ftppassword) {ftppassword = ftppassword; } public static string getEnveloperEsultroot () {return enveloperesultroot; } public static void setenveloperesultroot (String EnveloverEsultroot) {enveloperesultroot = enveloperesultroot; } public static void main (String args []) {new sysconstats (); }}파일 ftp : 업로드 :
package com.fz.fzbike.biz; import java.io.bufferedInputStream; import java.io.bytearRayoutputStream; import java.io.dataOutputStream; import java.io.fileInputStream; import java.io.filenotfoundection; import java.io.ioexmence; java.text.decimalformat; import com.enets.basesys.user.vo.uservo; import com.enets.framework.assemble.requesthashnew; import com.enets.framework.database.dbconnection; import com.fz.common.util.fileutil; import com.fz.fz.common.common com.fz.fzbike.domain.sysconstats;/** * 카드 코드를 FTP 서버에 업로드하여 BAT 파일을 생성하기 위해 FTP 서버에 업로드 * @Author wuxq 2011-09-28 */public class uploadcardinnoftPaction {/** * 메소드 이름 : Uploadftp 메소드 설명 : ftp * @void wux wux wux chux 28, 2011 10:38:38 AM */ public void uploadftp (requesthashnew reg) {String Cardtype = reg.get ( "cardtype"). toString (); dbConnection dbc = reg.getDBC (); // 링크 데이터베이스 dbc.endtran (); // 보고서 손실 여부를 결정하고 보고서 손실을 종료하고, 보고서 손실을 종료하고, 블랙리스트를 종료하고, 카드 ID를 기반으로 (StringUtil.isnull (cardtype)을 기준으로 카드 유형을 가져옵니다. cardtype = dbc.getList0 (cardtypesql); } string top = "c :/upload/"; 문자열 파일 = top + "bmc.dat"; // 임시 블랙리스트 배트 파일 문자열을 저장하는 디렉토리 정의 whitefile = top + "wmc.dat"; // 임시 화이트리스트 배트 파일 buserfile = top + "buser.dat"을 저장하는 디렉토리를 정의합니다. // 임시 검은 색 사용자 파일 문자열을 저장하는 디렉토리 정의 = dbc.setoracleGlideValue ( "lc_t_upgrade_file"); // 파일 테이블의 일련 번호 가져 오기 // 현재 사용자 id uservo uservo = rech.getUservo (); 문자열 userId = uservo.getUserId (); Decimalformat df = 새로운 십진형 ( "0.0"); if (cardtype.equals ( "7")) {StringBuffer bf = new StringBuffer (1024); bf .Append ( ""select card_in_no from (tc.card_in_no ") .Append ("LC_T_BLACKLIST TB 왼쪽 LING LING LC_T_CARD_INFO TC ") ") .append ("tc.card_in_no from lc_t_card_loss cl left join ") .append ("lc_t_card_info tc on cl.card_id = tc.card_id here tc.card_type = 7 and ") 블랙리스트 및 보고서 테이블 StringBuffer 브러시 = New StringBuffer (1024); bffer .append ( "lc_t_card_info ti에서 ti.card_in_no를 선택하십시오") .append ( "ti.card_type = 7 및 ti.card_make_status = 2 ti.card_in_no에 의한 주문"); // 모든 관리자 레코드에 대한 모든 관리자 레코드를 정의하십시오. arr [] [] = dbc.getarr (bf.tostring ()); // 카드 정보 테이블 문자열에 정렬 된 카드 코드를 수신 할 배열을 정의합니다. upload_f (arr, file); // 블랙리스트 BAT 파일의 버전 번호를 얻습니다. 초기 값은 1.0 String vectorsql = "file_vesion을 선택하십시오 (select row_number () over (t.file_vesion desc) num," + "t.file_vesion from t.file_type = 2) 여기서 num = 1"; 문자열 Vesion = dbc.getList0 (VesionsQl); Double VE = 1.0; // 블랙리스트 버전 번호 변수를 정의하면 초기 값은 1.0/ *입니다. 데이터베이스에 이전 버전이 있으면 0.1 */ if (stringUtil.isnotnull (Vesion)) {ve = (double.parsedouble (Vesion) + 0.1); } vesion = df.format (ve); // 버전 레코드 SQL 문자열 bmcsql = "lc_t_upgrade_file 값에 삽입합니다 (" + fileId + ", '" + file + "', '" + Vesion + "', '2', SysDate," + userId + "); dbc.insertdb (bmcsql); // 데이터베이스 업로드 _f (listarr, whitefile)에 지속됩니다. // 화이트리스트 된 BAT 파일의 버전 번호를 얻습니다. 초기 값은 1.0 String vesionsql2 = "file_vesion을 선택하십시오 (select row_number () Over (t.file_vesion desc) num," + "t.file_vesion lc_t_upgrade_file t there t.file_type = 5); String vesion2 = dbc.getList0 (Vesionsql2); Double Ve2 = 1.0; // 화이트리스트 버전 번호 변수를 정의하면 초기 값은 1.0/ *입니다. 데이터베이스에 이전 버전이 있으면 0.1 */ if (stringUtil.isnotnull (vesion2)) {ve2 = (double.parsedouble (vesion2) + 0.1); } 문자열 bfileid = dbc.setoracleGlideValue ( "lc_t_upgrade_file"); // 파일 테이블의 일련 번호를 가져옵니다 Vesion2 = df.format (VE2); // 버전 레코드 SQL 문 문자열 bmcsql2 = "lc_t_upgrade_file 값에 삽입 (" + bfileid + ", '" + WhiteFile + "', '" + Vesion2 + "', '5', SysDate," + userId + "); DBC.INSERTDB (BMCSQL2); // 데이터베이스에 지속} else {StringBuffer BF2 = New StringBuffer (1024); bf2 .Append ( "tc.card_in_no를 선택한 고유 한 card_in_no") Union All Select ") .Append ("LC_T_CARD_LOSS CL LEFT 조인의 "TC.CARD_IN_NO") .Append ( "LC_T_CARD_INFO TC ON CL.CARD_ID = TC.CARD_ID") t.card_in_no "); // 블랙리스트 테이블의 모든 비 관리기 레코드 및보고 된 사용자 테이블을보고했습니다. // 검은 색 사용자로 정렬 된 사용자 카드 코드를 수신 할 배열을 정의합니다. upload_f (arr2, buserfile); // 검은 색 사용자 BAT 파일의 버전 번호를 얻습니다. 초기 값은 1.0 String hsersql = "select file_vesion from (select row_number () Over (t.file_vesion desc) num," + "t.file_vesion from lc_t_upgrade_file t where t.file_type = 4); 문자열 vesion3 = dbc.getList0 (husersql); Double VES = 1.0; // 검은 색 사용자 버전 번호 변수를 정의하면 초기 값은 1.0/ *입니다. 데이터베이스에 이전 버전이있는 경우 버전이 0.1 */ if (StringUtil.isnotnull (vesion3)) {ves = (double.parsedouble (vesion3) + 0.1)로 증가합니다. } vesion3 = df.format (ves); // 버전 레코드 SQL 문자열 HUSERSQL = "LC_T_UPGRAGE_FILE 값에 삽입합니다 (" + fileId + ", '" + BuserFile + "', '" + Vesion3 + "', '4', SysDate," + userId + "); DBC.INSERTDB (HUSERSQL); // 데이터베이스에 지속}}/ ** * * 메소드 이름 : WriteLong 메소드 설명 : 출력 스트림에 긴 정수를 쓰기 * * @param input * @return byte [] 버전 1.0 저자 Wuxq Sep 28, 2011 10:54:58 AM */ Public Byte [] WriteLong (long input) = 새로운 BYTEARRAYOUTPUTSTREAM (); DataOutputStream OS = 새로운 DataOutputStream (BAOS); try {os.writelong (long.reversebytes (입력)); } catch (ioexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); } byte [] b = baos.tobytearray (); 반환 b; } / ** * * 메소드 이름 : UPLOAD_F 메소드 설명 : 파일을 FTP 서버에 업로드 * @param arr * @param 파일 * void 버전 1.0 저자 Wuxq 2011 11:37:27 AM * / public static void upload_f (string [] [] arr, String file) {byte by [] = null; 바이트 [] 결과 = 새로운 바이트 [1]; if (stringUtil.isnotnull (arr)) {result = new Byte [arr.length * 4]; int 위치 = 0; for (int i = 0; i <arr.length; i ++) {by = writelong (long.parselong (arr [i] [0])); 바이트 목록 [] = 새로운 바이트 [4]; for (int h = 0; h <list.length; h ++) {list [h] = by [h]; } for (int g = 위치; g <position+4; g ++) {result [g] = list [g -4 * i]; } 위치 = 위치 + 4; }} boolean bool = fileUtil.creatingWhiteManageFile (result, file); // BAT 파일 생성 if (bool) {// inputStreamReader isr = new inputStreamReader (new // fileInputStream (file)); inputStream inp = null; 입력 스트림 inp2 = null; try {inp = new bufferedInputStream (new FileInputStream (file)); inp2 = new bufferedInputStream (new FileInputStream (file)); } catch (filenotfoundException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); } // 파일 이름 문자열을 가로 채기 f = file.substring (10, file.length ()); // ftp 구성 정보 정보 sysconstats sc = new SysConstats (); FileUtil.uploadfileftp (Sc.ftpserver, Sc.ftpusername, Sc.ftppassword, Sc.EnveloperEsultroot, F, Inp, INP2); }}}Java 관련 컨텐츠에 대한 자세한 내용은이 사이트의 주제를 확인하십시오 : "Java 파일 및 디렉토리 운영 기술 요약", "Java 데이터 구조 및 알고리즘에 대한 자습서", "Java Operation Dom Node 작동 기술 요약"및 "Java Cache 운영 기술 요약".
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.