欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现将文件上传到ftp服务器的方法

程序员文章站 2024-03-31 21:18:04
本文实例讲述了java实现将文件上传到ftp服务器的方法。分享给大家供大家参考,具体如下: 工具类: package com.fz.common.util;...

本文实例讲述了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;
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 26, 2011 10:17:39 am
 * @return
 * @author zhangh
 */
 public static datainputstream 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 26, 2011 10:17:44 am
 * @param whites
 * @return
 * @author zhangh
 */
 public static boolean creatwhitemanagefile(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 16, 2011 4:39:22 pm
 * @param url
 * @param username
 * @param password
 * @param path
 * @param filename
 * @param input
 * @return
 * @author zhangh
 */
 public static boolean uploadfile(string url, string username,
  string password, string path, string filename, inputstream input) {
 boolean success = false;
 ftpclient ftp = new ftpclient();
 try {
  int reply;
  ftp.connect(url);
//  ftp.connect(url, port);// 连接ftp服务器
  // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接ftp服务器
  ftp.login(username, password);// 登录
  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;
 }
 /**
 *
 * 方法名称:uploadfileftp
 * 方法描述:黑名名单,黑用户文件上传ftp服务器
 * @param url
 * @param username
 * @param password
 * @param path
 * @param filename
 * @param input
 * @param input2
 * @return
 * boolean
 * version 1.0
 * author wuxq
 * oct 26, 2011 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);// 登录
  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;
 }
}

读取配置文件:

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;
/**
 * 获取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服务器用户名
 public static string ftppassword;// ftp服务器用户密码
 public static string enveloperesultroot;// 存放ftp服务器的路径
 public sysconstats() {
 try {
  inputstream in = new bufferedinputstream(new fileinputstream(
   sysconstants.public_path.substring(0,
    sysconstants.public_path.length() - 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("读取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 enveloperesultroot) {
 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.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;
/**
 * 上传卡内码到ftp服务器 生成bat文件
 *
 * @author wuxq 2011-09-28
 */
public class uploadcardinnoftpaction {
 /**
 *
 * 方法名称:uploadftp 方法描述:上传文件到ftp
 *
 * @param reh
 *      void version 1.0 author wuxq sep 28, 2011 10:38:38 am
 */
 public void uploadftp(requesthashnew reh) {
 string cardtype = reh.get("cardtype").tostring();
 dbconnection dbc = reh.getdbc();// 链接数据库
 dbc.endtran();
 // 判断是否是空值 空有可能是挂失,退出挂失, 退出黑名单, 根据卡id得到卡类型
 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"; // 定义一个目录存放临时的黑名单bat文件
 string whitefile = top + "wmc.dat";// 定义一个目录存放临时的白名单bat文件
 string buserfile = top + "buser.dat"; // 定义一个目录存放临时的黑用户文件
 string fileid = dbc.setoracleglidevalue("lc_t_upgrade_file");// 得到文件表的序列号
 // 得到当前用户的id
 uservo uservo = 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 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 where tc.card_type = 7 and")
   .append(" cl.whether_effective=1) t order by t.card_in_no");// 黑名单及挂失记录表中所有的管理员记录
  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_status=2 order by ti.card_in_no");// 卡信息表中所有的管理员记录
  // 定义一个数组来接收黑名单中排序好的管理员卡内码
  string arr[][] = dbc.getarr(bf.tostring());
  // 定义一个数组来接收卡信息表中排序好的管理员卡内码
  string listarr[][] = dbc.getarr(bffer.tostring());
  upload_f(arr, file);
  // 得到黑名单bat文件的版本号, 初始值为1.0
  string vesionsql = "select file_vesion from(select row_number() over(order by t.file_vesion desc) 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;// 定义黑名单版本编号变量,初始值为1.0
  /*
  * 数据库中存在旧版本则在版本增加0.1
  */
  if (stringutil.isnotnull(vesion)) {
  ve = (double.parsedouble(vesion) + 0.1);
  }
  vesion = df.format(ve);
  // 版本记录sql语句
  string bmcsql = "insert into lc_t_upgrade_file values(" + fileid
   + ",'" + file + "','" + vesion + "','2',sysdate," + userid
   + ")";
  dbc.insertdb(bmcsql);// 持久化到数据库
  upload_f(listarr, whitefile);
  // 得到白名单bat文件的版本号, 初始值为1.0
  string vesionsql2 = "select file_vesion from(select row_number() over(order 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;// 定义白名单版本编号变量,初始值为1.0
  /*
  * 数据库中存在旧版本则在版本增加0.1
  */
  if (stringutil.isnotnull(vesion2)) {
  ve2 = (double.parsedouble(vesion2) + 0.1);
  }
  string bfileid = dbc.setoracleglidevalue("lc_t_upgrade_file");// 得到文件表的序列号
  vesion2 = df.format(ve2);
  // 版本记录sql语句
  string bmcsql2 = "insert into lc_t_upgrade_file values(" + bfileid
   + ",'" + whitefile + "','" + vesion2 + "','5',sysdate,"
   + userid + ")";
  dbc.insertdb(bmcsql2);// 持久化到数据库
 } 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");// 黑名单表及挂失用户表中所有非管理员记录
  // 定义一个数组来接收黑用户中排序好的用户卡内码
  string arr2[][] = dbc.getarr(bf2.tostring());
  upload_f(arr2, buserfile);
  // 得到黑用户bat文件的版本号, 初始值为1.0
  string husersql = "select file_vesion from(select row_number() over(order by t.file_vesion desc) 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;// 定义黑用户版本编号变量,初始值为1.0
  /*
  * 数据库中存在旧版本则在版本增加0.1
  */
  if (stringutil.isnotnull(vesion3)) {
  ves = (double.parsedouble(vesion3) + 0.1);
  }
  vesion3 = df.format(ves);
  // 版本记录sql语句
  string husersql = "insert into lc_t_upgrade_file values(" + fileid
   + ",'" + buserfile + "','" + vesion3 + "','4',sysdate,"
   + userid + ")";
  dbc.insertdb(husersql);// 持久化到数据库
 }
 }
 /**
 *
 * 方法名称:writelong 方法描述:向输出流中写长整型
 *
 * @param input
 * @return byte[] version 1.0 author wuxq sep 28, 2011 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;
 }
 /**
 *
 * 方法名称:upload_f 方法描述:把文件上传到ftp服务器
 *
 * @param arr
 * @param file
 *      void version 1.0 author wuxq oct 8, 2011 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);// 创建一个bat文件
 if (bool) {
  // inputstreamreader isr = new 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();
  }
  // 截取文件名
  string 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操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。