JAVA Learning (1) _ operate FTP

Source: Internet
Author: User

[Html] // FFP initializes the connection public static void init () {Properties config = new Properties (); try {System. out. println ("access ftp. properties "); // read the configuration file InputStream inputStream = FTPUtils. class. getClassLoader (). getResourceAsStream ("/ftp. properties "); config. load (inputStream); // FTP Server IP serverIP = config. getProperty ("ftp. serverName "); // FTP server port = config. getProperty ("ftp. port "); // FTP Server userName = config. GetProperty ("ftp. userName"); // FTP server password = config. getProperty ("ftp. password"); // server name. (The file name assembled here, for example, report_2013_02_01.csv) FTPConst. REMORT_FILE_NAME = config. getProperty ("ftp. reportDateFile ") + getFtpDay () + ". csv "; FTPConst. LOCAL_FILE_NAME = config. getProperty ("local. reportDateFile ") + getFtpDay () + ". csv "; FTPConst. FTP_REPORT_FLOW_BROWSERS_FILE_NAME = config. getProperty ("ftp. browsersMonthFile ") + getFtpMonth () + ". csv "; FTPConst. LOCAL_REPORT_FLOW_BROWSERS_FILE_NAME = config. getProperty ("local. B RowsersMonthFile ") + getFtpMonth () + ". csv ";} catch (Exception e) {e. printStackTrace (); logger. error ("ftp. failed to load properties: ", e) ;}/ *** obtain the name of the BROWSERS report and obtain the previous month. For example, it is now in December February. Obtain the String 2012-01 * @ return */public static String getFtpMonth () {Date date = new Date (); Calendar ar cal = Calendar ar. getInstance (); cal. setTime (date); cal. add (Calendar. MONTH,-1); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM"); String dateStr = sdf. format (cal. getTime (); return dateStr;}/*** get the name of the daily OMNITURE report and the previous day. For example, this is July 22, February 22, 2013. Obtain the String: February 21, 2013 * @ return */public static String getFtpDay () {Date date Date = new Date (); Calendar ar cal = Calendar ar. getInstance (); cal. setTime (date); cal. add (Calendar. DAY_OF_MONTH,-1); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd"); String dateStr = sdf. format (cal. getTime (); // System. out. println (dateStr); return dateStr;}/*** download the FTP server file to the local device and return the local file. * @ Param remoteFileName * @ param localFileName * @ return */public static synchronized String downloadFile (String remoteFileName, String localFileName) {try {File localFile = new File (localFileName ); // if the object does not exist. Create this file if (! LocalFile. exists () {localFile. createNewFile ();} else {logger.info ("the file already exists"); return localFileName;} OutputStream output = new FileOutputStream (localFile); FTPClient client = new FTPClient (); client. connect (serverIP); client. login (userName, password); boolean flag = client. retrieveFile (remoteFileName, output); client. logout (); if (flag) {return localFileName;} else {return null ;}} catch (Exception E) {e. printStackTrace (); logger. error ("omniture data download error:", e); return null ;}} /*** use javacsv to parse csv files * @ param file * @ return */private List <OmnitureReportBean> javaCsv (String file) {try {List <OmnitureReportBean> omnitureList = new ArrayList <OmnitureReportBean> (); CsvReader reader = new CsvReader (file, ',', Charset. forName ("UTF-8"); int I = 0; while (reader. readRecord () {// skip useless rows. If (I ++ <= 15) {String [] str = reader. getValues (); System. out. println ("number:" + (I-1) + str [0]); continue;} // read each row of data returns String [] str = reader in an array. getValues (); OmnitureReportBean omniture = new OmnitureReportBean (); String timeStr = file. trim (). substring (21, 28); Date date = smipleDateFormat. parse (timeStr); omniture. setStartTime (date); omniture. setEndTime (date); omniture. setBrowsers (str [0]); omnitur E. setVisits (new Integer (str [1]. replace (",",""). trim (); omniture. setSearches (new Integer (str [2]. replace (",",""). trim (); omniture. setCardAdd (new Integer (str [3]. replace (",",""). trim (); omniture. setCheckOuts (new Integer (str [4]. replace (",",""). trim (); omniture. setPament (new Integer (str [5]. replace (",",""). trim (); omniture. setOrders (new Integer (str [6]. replace (",",""). trim (); omniture. se TType (2); omnitureList. add (omniture); List <OmnitureReportBean> list = this. omnitureDao. findOmnitureMonthList (omniture. getStartTime (), omniture. getBrowsers (); // if the table already contains data for this time period, the data in this csv will not be inserted repeatedly if (list! = Null & list. size ()> 0) {continue;} else {omnitureDao. saveOmniture (omniture) ;}return omnitureList;} catch (Exception e) {e. printStackTrace (); return null ;}/ *** compared with the current date. If true is returned earlier than the current time. otherwise, false * @ param endDate * @ return */public static boolean compareToDate (Date date) {Calendar cal1 = Calendar. getInstance (); Calendar cal2 = Calendar. getInstance (); Date nowDate = new Date (); cal1.setTime (date); cal1.add (Calendar ar. HOUR_OF_DAY, 00); cal1.add (Calendar. MINUTE, 00); cal1.add (Calendar. SECOND, 00); cal2.setTime (nowDate); cal2.add (Calendar. HOUR_OF_DAY, 00); cal2.add (Calendar. MINUTE, 00); cal2.add (Calendar. SECOND, 00); boolean flag = cal1.before (cal2); if (flag) {// return true before the current system time ;} else {// return false later than the current system time ;}} /*** delete the file on the server * @ param path * @ return * @ throws IOException */public boolean delFile (String path) throws IOException {boolean flag = false; FTPClient client = new FTPClient (); Date currentTime = new Date (); SimpleDateFormat formatter = new SimpleDateFormat ("yyMMdd"); String dateString = formatter. format (currentTime); String fileName = "Report.csv"; try {client. connect (serverIP); client. login (userName, password); client. enterLocalPassiveMode (); client. setFileType (FTP. BINARY_FILE_TYPE); client. changeWorkingDirectory (path); client. deleteFile (path + fileName); flag = true; logger.info ("file: [" + path + fileName + "] is deleted on ftp:" + serverIP );} catch (Exception e) {flag = false;} finally {try {client. disconnect ();} catch (IOException e) {logger.info ("disconnect FTP failed:" + e. getMessage () ;}} return flag ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.