Java implementation to upload files to the FTP server method _java

Source: Internet
Author: User
Tags file upload stringbuffer

The example of this article describes how the Java implementation uploads files to an FTP server. Share to everyone for your reference, specific as follows:

Tool class:

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;
Import Java.io.InputStream;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import org.apache.commons.net.ftp.FTPClient;
Import org.apache.commons.net.ftp.FTPReply; public class Fileutil {/** * * @date Sep, 10:17:39 AM * @return * @author zhangh/public static Datainpu
 Tstream GetInput () {DataInputStream d = null;
  try {d = new DataInputStream (New FileInputStream ("C:/wmc.dat"));
 return D;
 catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
 return D; /** * * @date Sep, 10:17:44 AM * @param whites * @return * @author Zhangh/public static Boolean creat
 Whitemanagefile (byte[] whites,string file) {DataOutputStream D; try {d = new DataOutputStream (New FILEOUTPUTSTReam (file));
  D.write (whites);
 D.flush ();
 catch (Exception e) {//TODO auto-generated catch block return false;//E.printstacktrace ();
 return true; /** * * @date Sep, 4:39:22 PM * @param URL * @param username * @param password * @param path * @param fi Lename * @param input * @return * @author Zhangh/public static Boolean uploadfile (string URL, string username, S
 Tring Password, string path, string filename, InputStream input) {Boolean success = false;
 ftpclient ftp = new FtpClient ();
  try {int reply;
Ftp.connect (URL); Ftp.connect (URL, port);//Connect FTP server//If the default port is used, you can connect the FTP server directly using the Ftp.connect (URL) ftp.login (username, password);
  Login reply = Ftp.getreplycode (); if (!
  Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect ();
  return success;
  } ftp.changeworkingdirectory (path);
  Ftp.storefile (filename, input);
  Ftp.logout ();
  Input.close ();
 Success = true;
 catch (IOException e) {e.printstacktrace (); } finally {if (ftp.isconnected ()) {try {ftp.disconnect ();
 catch (IOException IoE) {}} return success; /** * * Method Name: Uploadfileftp * Method Description: Black Name list, black user File upload ftp server * @param URL * @param username * @param password * @param p ATH * @param filename * @param input * @param input2 * @return * Boolean * Version 1.0 * Author Wuxq * OCT 26, 201 1 3:19:09 PM */public static Boolean uploadfileftp (string URL, string username, string password, string path, string
 FileName, InputStream input, InputStream input2) {Date date = new Date ();
 SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
 String time = Formatter.format (date);
 Boolean success = false;
 ftpclient ftp = new FtpClient ();
  try {int reply;
  Ftp.connect (URL);
  Ftp.login (username, password);/Login reply = Ftp.getreplycode (); if (!
  Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect ();
  return success;
  } ftp.changeworkingdirectory (path); Ftp.storefile (filename, INPUT);
  Ftp.storefile (filename + time, input2);
  Ftp.logout ();
  Input.close ();
 Success = true;
 catch (IOException e) {e.printstacktrace ();
  finally {if (ftp.isconnected ()) {try {ftp.disconnect ();
 catch (IOException IoE) {}} return success;

 }
}

Read configuration file:

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.eNets.framework.util.SysConstants; /** * Get FTP Server information Bean class * * @author WUXQ * * */public class Sysconstats {private static Logger log = Logger.getlogger
 (Sysconstats.class); public static string ftpserver;//FTP server IP address public static string ftpusername;//FTP server user name public static string FTPPASSW ord;//FTP Server user password public static String enveloperesultroot;//the path to the FTP server public sysconstats () {try {InputStream in = new Bufferedinputstream (new FileInputStream (SysConstants.PUBLIC_PATH.substring 0, SysConstants.PUBLIC_PATH.lengt
  H ()-7) + "/bidfileconfig.properties");
  Properties prop = 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 ("Read FTP configuration information successfully!")
 "); catch (IOException e) {Log.debug ("failed to read FTP configuration information!")
  ");
 E.printstacktrace ();
 } public static String Getftpserver () {return ftpserver;
 The public static void Setftpserver (String ftpserver) {ftpserver = Ftpserver;
 public static String Getftpusername () {return ftpusername;
 The public static void Setftpusername (String ftpusername) {ftpusername = FtpUserName;
 public static String Getftppassword () {return ftppassword;
 The public static void Setftppassword (String ftppassword) {FTPPassword = FTPPassword;
 public static String Getenveloperesultroot () {return enveloperesultroot;
 The public static void Setenveloperesultroot (String enveloperesultroot) {enveloperesultroot = Enveloperesultroot;
 public static void Main (String args[]) {new sysconstats ();

 }
}

Upload files to 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.FileNotFoundException;
Import java.io.IOException;
Import Java.io.InputStream;
Import 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.fzbike.common.StringUtil;
Import Com.fz.fzbike.domain.SysConstats; /** * Upload card inside code to FTP server generate BAT file * * @author WUXQ 2011-09-28/public class Uploadcardinnoftpaction {/** * * Method Name: Uploa Dftp method Description: Upload file to FTP * * @param reh * Void version 1.0 author Wuxq Sep, 10:38:38 AM/public void UPLOADF
 TP (requesthashnew reh) {String Cardtype = reh.get ("Cardtype"). ToString ();
 DbConnection DBC = Reh.getdbc ();//Link Database Dbc.endtran (); To determine whether empty values may be reported loss, exit loss, exit blacklist, according to Card ID get card type if (Stringutil.isnull CARdtype)) {String cardtypesql = "Select Ci.card_type from Lc_t_card_info ci where ci.card_id=" + reh.get ("Selectedid"
  );
 Cardtype = Dbc.getlist0 (Cardtypesql);
 } String top = "c:/upload/"; String file = top + "Bmc.dat"; Define a directory to store temporary blacklist bat files String whitefile = top + "Wmc.dat";//define a directory to store temporary whitelist bat file string buserfile = top + "Buser.dat"; Define a directory to store temporary black user files String Fileid = Dbc.setoracleglidevalue ("Lc_t_upgrade_file");//Get the serial number of the file table//Get the current user ID Uservo userv
 o = Reh.getuservo ();
 String UserID = Uservo.getuserid ();
 DecimalFormat df = new DecimalFormat ("0.0");
  if (Cardtype.equals ("7")) {stringbuffer BF = new StringBuffer (1024); BF. Append ("SELECT DISTINCT Card_in_no from (select Tc.card_in_no"). Append ("From Lc_t_blacklist TB left J oin lc_t_card_info TC "). Append (" On tb.card_id = tc.card_id where Tc.card_type = 7 "). Append (" and Tb.whether_ Effective = 1 UNION ALL Select "). 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 where Tc.card_type = 7 and"). Append ("cl.whether_effective=1) t Orde
  R by T.card_in_no ")//blacklist and report loss records all the Administrator records StringBuffer Bffer = new StringBuffer (1024); Bffer. Append ("Select Ti.card_in_no from Lc_t_card_info ti"). Append ("Where ti.card_type=7 and Ti.card_make_st atus=2 ORDER by Ti.card_in_no ");//card information table all admin records//define an array to receive the sorted administrator card inside code String arr[][in The blacklist = Dbc.getarr (Bf.tostring ())
  ;
  Defines an array to receive the sorted administrator card within the Card information table String listarr[][] = Dbc.getarr (bffer.tostring ());
  Upload_f (arr, file); Gets the version number of the blacklist bat file, with the initial value 1.0 String vesionsql = "Select File_vesion from" (Select Row_number ()-by-T.file_vesion D
  ESC) num, "+" t.file_vesion from Lc_t_upgrade_file t where t.file_type=2) where num=1 ";
  String vesion = dbc.getlist0 (Vesionsql); Double ve = 1.0;//defines the blacklist version number variable, the initial value is 1.0 * * * The old version in the database is added 0.1/if (Stringutil.isnotnull (vesion)) {ve = (Doub
  Le.parsedouble (vesion) + 0.1); } vesion = Df.format (ve); Version record SQL statement String bmcsql = "INSERT INTO Lc_t_upgrade_file values (" + Fileid + ", '" + File + "', '" + vesion + "', ' 2 ')
  , sysdate, "+ UserID +") ";
  Dbc.insertdb (bmcsql);//persisted to the database Upload_f (Listarr, whitefile); Gets the version number of the whitelist bat file, with the initial value 1.0 String vesionSql2 = "Select File_vesion from" (Select Row_number ()-by-t.file_vesion
  DESC) num, "+" t.file_vesion from Lc_t_upgrade_file t where t.file_type=5) where num=1 ";
  String Vesion2 = dbc.getlist0 (VESIONSQL2); Double ve2 = 1.0;//defines a whitelist version number variable with an initial value of 1.0 * * * The old version in the database is incremented in the version 0.1 */if (Stringutil.isnotnull (Vesion2)) {ve2 = (D
  Ouble.parsedouble (Vesion2) + 0.1);
  String Bfileid = Dbc.setoracleglidevalue ("Lc_t_upgrade_file");//Get the serial number of the file table Vesion2 = Df.format (ve2); Version record SQL statement String BMCSQL2 = "INSERT INTO Lc_t_upgrade_file values (" + Bfileid + ", '" + Whitefile + "', '" + vesion2
  + "', ' 5 ', sysdate," + UserID + ")"; Dbc.insertdb (BMCSQL2),//persisted to the database} else {StringBuffer bf2 = new StringbuffeR (1024);  Bf2. Append ("SELECT DISTINCT Card_in_no from (select Tc.card_in_no"). Append ("from Lc_t_blacklist TB left Join Lc_t_card_info TC "). Append (" On tb.card_id = tc.card_id where Tc.card_type <> 7 "). Append (" and TB . whether_effective = 1 UNION ALL Select "). 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 "). Append (" Where Tc.card_type <> 7 and Cl.whether_effective "). Append ("= 1) t order by t.card_in_no");//blacklist table and all Non-administrator records in the report Loss user table define an array to receive the sorted user card inside code String arr2[][of the Black user = Dbc.getarr (bf2.to
  String ());
  Upload_f (ARR2, buserfile); Gets the version number of the black user bat file, with the initial value of 1.0 String husersql = "Select File_vesion from" (Select Row_number ()-by-T.file_vesion DE
  SC) num, "+" t.file_vesion from Lc_t_upgrade_file t where t.file_type=4) where num=1 ";
  String Vesion3 = dbc.getlist0 (Husersql); Double ves = 1.0;//defines the black user version number variable with an initial value of 1.0 * * * The old version in the database is added 0.1/if (S)Tringutil.isnotnull (Vesion3)) {ves = (double.parsedouble (vesion3) + 0.1);
  } Vesion3 = Df.format (ves); Version record SQL statement String husersql = "INSERT INTO Lc_t_upgrade_file values (" + Fileid + ", '" + Buserfile + "', '" + Vesion3
  + "', ' 4 ', sysdate," + UserID + ")"; Dbc.insertdb (Husersql),//persisted to the database}/** * * Method Name: Writelong method Description: Write long integer to output stream * * @param input * @return byte[] Vers  Ion 1.0 author Wuxq Sep, 10:54:58 AM */public static byte[] Writelong (Long input) {Bytearrayoutputstream BAOs
 = new Bytearrayoutputstream ();
 DataOutputStream OS = new DataOutputStream (BAOs);
 try {os.writelong (long.reversebytes (input));
 catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 } byte[] B = Baos.tobytearray ();
 return b; /** * * Method Name: Upload_f method Description: Upload file to FTP server * * @param arr * @param file * Void version 1.0 author Wuxq Oct 8, 2 011 11:37:27 AM */public static void Upload_f (string[][] arr, String file) {byte by[] = Null
 Byte[] result = new BYTE[1];
  if (Stringutil.isnotnull (arr)) {result = new byte[arr.length * 4];
  int position = 0;
  for (int i = 0; i < arr.length i++) {by = Writelong (Long.parselong (arr[i][0)));
  byte list[] = new BYTE[4];
  for (int h = 0; h < list.length; h++) {list[h] = by[h];
  for (int g = Position g < position + 4; g++) {Result[g] = list[g-4 * I];
  } position = position + 4; boolean bool = Fileutil.creatwhitemanagefile (result, file);//Create a BAT file if (bool) {//InputStreamReader ISR = NE
  W InputStreamReader (New//FileInputStream (file));
  InputStream INP = null;
  InputStream inp2 = null;
  try {inp = new Bufferedinputstream (new FileInputStream (file));
  INP2 = new Bufferedinputstream (new FileInputStream (file));
  catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
  //intercept filename String f = file.substring (File.length ()); Get FTP configuration information Sysconstats sc = new sysconstats ();
  Fileutil.uploadfileftp (SC. Ftpserver, SC. FtpUserName, SC. FTPPassword, SC.
 Enveloperesultroot, F, INP, INP2);

 }
 }
}

More about Java-related content readers can view the site topics: "Java files and directory operation tips Summary", "Java Data structure and algorithm tutorial", "Java Operation DOM node skills summary" and "Java Cache Operation Tips Summary"

I hope this article will help you with Java programming.

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.