好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java对文本文件MD5加密并ftp传送到远程主机目录的实现方法

需求描述:

客户出完账之后需要把出账的数据以文本文件的方式传送给收入管理系统,客户以前是通过本地的一个工具软件上传的,由于安全监管的原因,不允许在本地使用工具上传,因此客户希望我们在已经上线使用的系统开发一个功能实现他们的需求。

业务梳理:

我梳理一下具体的细节,具体的流程如图所示:

程序实现:

一、首先是设计页面

由于是在原系统的基础上新增功能,需要提前做好菜单的配置工作。我设计的页面如下图,一个是下拉选择框(用户选择相对应的业务),一个是选择文件,一个是月份(表示需要传送的文件是哪个月),一个是上传按钮,用户选择文件之后选择月份点击上传按钮之后即可触发上传操作。

以下是jsp界面的源码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<%@ include file= "/common/taglibs.jsp" %>

<%@ page language= "java" pageencoding= "utf-8" %>

<%@ page iselignored= "false" %>

<s:form enctype= "multipart/form-data" method= "post" onsubmit= "return valid();" >

<page:applydecorator name= "simplequery" >

<table cellspacing= "1" border= "0" >

<title><s:text name= "erp接口上传小程序" /></title>

<s:hidden name= "filename" ></s:hidden>

<tr><td>业务类型

  <select id= "" name= "operationtype" class = "formselect" >

  <option></option>

  <option value= "1" >集团预出账</option>

  <option value= "2" >集团正式出账</option>

  </select>

</td>

<td>接口月份:

<as:datepicker id= "startdate" name= "rpmonth" readonly= "false" disabled= "false"

formatflag= "date6" showdefault= "true" cssclass= "required validate-datetime" >  </as:datepicker>

</td> 

</tr>

<tr><td width= "10%" >选择文件

<s:file id= "upload" name= "upload" ></s:file>

</td>

<td >

 

</td>

<td >

<input id= "impbut" type= "button" value= "上传" onclick= "importhandle()" class = "button" />

</td>           

</tr>

</table>

</page:applydecorator> 

</s:form>

<script type= "text/javascript" >

function importhandle() {

var filename = $( 'upload' ).value;

if (filename == null || filename == undefined || filename == "" ) {

  validation.userdefined( "请选择要上传的文件" );

  return ;

  }

  filename = filename.split( "." );

if (filename[filename.length - 1 ] == "txt" || filename[filename.length - 1 ] == "txt" ) {

  document.forms[ 0 ].action = "interfaceupload_upload_interfaceupload.do" ;

  document.forms[ 0 ].submit();

  } else {

  validation.userdefined( "文件格式错误,您上传的格式不被允许" );

  return ;

  }

}

</script>

二、点击上传按钮之后的函数为:importhandle(),提交的请求为interfaceupload_upload_interfaceupload.do

?

1

<input id= "impbut" type= "button" value= "上传" onclick= "importhandle()" class = "button" />

系统是由struts2实现的,因此要在配置中加入这一段请求相对应的action的配置

?

1

2

3

4

5

6

<!-- erp接口文件上传 -->

<action name= "interfaceupload_upload_interfaceupload"

class = "aicu.application.mps.voice.international.web.revenue.fileimportaction" >

<result name= "success" >/web-inf/jsp/revenue/interfaceupload.jsp</result>

<param name= "uploadserviceid" >interfaceupload</param>

</action>

三、做好了相对应的准备工作,继续来写接下来的业务逻辑。

编写aicu.application.mps.voice.international.web.revenue.fileimportaction类

?

1

2

3

4

5

6

7

8

9

package aicu.application.mps.voice.international.web.revenue; 

import aicu.application.mps.voice.international.web.revenue.fileuploadaction;

public class fileimportaction extends fileuploadaction {

  public string execute() throws exception {

   system.out.println( "hello" );

   smartupload();

   return success;

  }

}

由于fileimportaction继承了fileuploadaction,所以相对应的请求都会由>fileuploadaction的execute()来处理。

首先是获取上传上来的文件对象,通过声明上传文件的对象,内容类型,文件名,服务id,然后在生成set()方法和get()方法便能获取到文件对象。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

protected file upload; // 实际上传文件

protected string uploadcontenttype; // 文件的内容类型

protected string uploadfilename; // 上传文件名

protected string uploadserviceid; //上传服务id

 

public file getupload() {

  return upload;

  }

 

public void setupload(file upload) {

  this .upload = upload;

  }

public string getuploadcontenttype() {

  return uploadcontenttype;

  }

 

public void setuploadcontenttype(string uploadcontenttype) {

  this .uploadcontenttype = uploadcontenttype;

  }

 

public string getuploadfilename() {

  return uploadfilename;

  }

 

public void setuploadfilename(string uploadfilename) {

  this .uploadfilename = uploadfilename;

  }

 

public string getuploadserviceid() {

  return uploadserviceid;

  }

 

public void setuploadserviceid(string uploadserviceid) {

  this .uploadserviceid = uploadserviceid;

  }

然后是对当前的文本文件进行md5加密,生成同名的md5文件,文件中只有一行加密之后的md5字符串。

由于通过struts上传的文件是存放在临时目录下,我处理的思路是,先把文件copy到指定的路径下

?

1

2

3

4

5

string datapath = getrealpath()+ "upload" +file.separator+uuid.randomuuid()+file.separator;

file newfile= new file( new file(datapath),uploadfilename);

if (!newfile.getparentfile().exists())

  newfile.getparentfile().mkdirs();

fileutils.copyfile(upload, newfile);

然后是生成md5同名文件

?

1

2

filemd5 filemd5= new filemd5();

string md5str=filemd5.getmd5(newfile);

实现的思路是调用bytetohexstring方法得到加密之后md5的字符串,通过writefilecontent实现把文本写入同名的md5文件中。filemd5类的getmd5(file file)方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

public string getmd5(file file) {

  boolean bool = false ;

  fileinputstream fis = null ;

  string filename=file.getname();

  string[] newfilepath=filename.split( "\\." );

  string filenametemp = file.getparent()+file.separator+newfilepath[ 0 ]+ ".md5" ;

 

  file md5file = new file(filenametemp);

  try {

  messagedigest md = messagedigest.getinstance( "md5" );

  fis = new fileinputstream(file);

  byte [] buffer = new byte [ 2048 ];

  int length = - 1 ;

  long s = system.currenttimemillis();

  while ((length = fis.read(buffer)) != - 1 ) {

  md.update(buffer, 0 , length);

  }

  byte [] b = md.digest();

  string filecontent=bytetohexstring(b);

  if (!md5file.exists()) {

  md5file.createnewfile();

  bool = true ;

  system.out.println( "success create file,the file is "

   + md5file.getname());

  writefilecontent(filenametemp, filecontent);

  }

  else {

  md5file.delete();

  system.out.println( "success delete file,the file is "

   + md5file.getname());

  md5file.createnewfile();

  bool = true ;

  system.out.println( "success create file,the file is "

   + md5file.getname());

  writefilecontent(filenametemp, filecontent);

  }

  return bytetohexstring(b);

  } catch (exception ex) {

  ex.printstacktrace();

  return null ;

  } finally {

  try {

  fis.close();

  } catch (ioexception ex) {

  ex.printstacktrace();

  }

  }

  }

bytetohexstring方法,主要是实现对文本文件的md5加密,得到加密之后的md5文件

?

1

2

3

4

5

6

7

8

9

10

11

12

private string bytetohexstring( byte [] tmp) {

  string s;

  char str[] = new char [ 16 * 2 ];

  int k = 0 ;

  for ( int i = 0 ; i < 16 ; i++) {

  byte byte0 = tmp[i];

  str[k++] = hexdigits[byte0 >>> 4 & 0xf ];

  str[k++] = hexdigits[byte0 & 0xf ];

  }

  s = new string(str);

  return s;

  }

writefilecontent方法,实现把文本写入同名的md5文件中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

public boolean writefilecontent(string filepath, string newstr) throws ioexception {

  boolean bool = false ;

   //string filein = newstr + "\r\n";

  string filein = new string(newstr);

  string temp = "" ;

 

  fileinputstream fis = null ;

  inputstreamreader isr = null ;

  bufferedreader br = null ;

  fileoutputstream fos = null ;

  printwriter pw = null ;

  try {

  file file = new file(filepath);

  fis = new fileinputstream(file);

  isr = new inputstreamreader(fis);

  br = new bufferedreader(isr);

  stringbuffer buffer = new stringbuffer();

   for ( int i = 0 ; (temp = br.readline()) != null ; i++) {

    buffer.append(temp);

    buffer = buffer.append(system.getproperty( "line.separator" ));

    }

    buffer.append(filein);

 

    fos = new fileoutputstream(file);

    pw = new printwriter(fos);

    pw.write(buffer.tostring().tochararray());

    pw.flush();

    bool = true ;

   } catch (exception e) {

    e.printstacktrace();

   } finally {

    if (pw != null ) {

     pw.close();

    }

    if (fos != null ) {

     fos.close();

    }

    if (br != null ) {

     br.close();

    }

    if (isr != null ) {

     isr.close();

    }

    if (fis != null ) {

     fis.close();

    }

   }

   return bool;

  }

四、获取到文本文件和生成同名的文件名之后,紧接着就是获取相对应的 ftp 主机,用户名,密码以及路径信息了。我把这相对应的信息保存在数据库中。首先我们把获取到的业务类型放入一个hashmap中。

?

1

2

parametermap= new hashmap();

parametermap.put( "audit_flag" ,operationtype);

然后我们配置ibaits的sqlid

?

1

2

3

4

5

6

7

8

9

10

<!-- 根据业务选择路径,zhongfs于 2017 - 12 - 05 添加 -->

<select id= "checkftptype" resultclass= "java.util.linkedhashmap" >

select ftphost, proguser, progpass, remotedirectory from t_ftp_config s

where 1 = 1

<isnotempty prepend= "and" property= "audit_flag" >

<![cdata[ 

s.audit_flag = #audit_flag#

]]>

</isnotempty>

</select>

然后执行该sqlid的查询,把结果放入list 中

?

1

list<map> resulttype=easydatafatcheronibatis.querybysqlkey( "checkftptype" , false ,parametermap);

下面是根据该sqlid查询出来的list结果中,取出相关的信息

?

1

2

3

4

5

6

string host = (string)resulttype.get( 0 ).get( "ftphost" );

string user = (string)resulttype.get( 0 ).get( "proguser" );

string pass = (string)resulttype.get( 0 ).get( "progpass" );

string path = (string)resulttype.get( 0 ).get( "remotedirectory" );

//每月会自动生成一个月份的子目录

string relpath=path+rpmonth+ "/" ;

至此,便可以获取到相对应的ftp主机,用户名,密码以及路径信息了。

五、最后一步是实现上传,我是用的ftpclient来实现的。

实现的操作都写在了ftpbbsutil的ftpsento方法中,其中datapath表示需要传送文件的目录。

?

1

ftpbbsutil.getftpbbs().ftpsento(datapath, host, user, pass, relpath);

ftpbbsutil的ftpsento方法如下所示:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public void ftpsento(string localpath, string host, string user,

  string pass, string path) throws exception {

  login(host, 21 , user, pass);

  file parentfile = new file(localpath);

  file[] files = parentfile.listfiles();

  string outpath = path;

  for (file afile : files) {

   if (afile != null && afile.getname() != null ) {

    put(afile, outpath, new string((afile.getname())

    .getbytes( "gb18030" ), "iso8859-1" ));

   }

  }

  logout();

}

总结

本篇文章描写了java如何实现对某一目录下的文件夹下的文本文件实现md5加密,并生成同名的md5文件,根据配置信息,获取主机ip,用户名密码,传送的路径,然后实现ftp远程传送功能。如果你有类似的需求,希望可以帮助到你,或者你能从中获取到灵感。

原文链接:https://www.cnblogs.com/zhongfengshan/p/9396852.html

查看更多关于Java对文本文件MD5加密并ftp传送到远程主机目录的实现方法的详细内容...

  阅读:50次