In EDI Java through FTP tool to achieve file upload download instance _java

Source: Internet
Author: User
Tags ftp connection ftp file ftp upload file ftp file transfer

Recently took over an EDI project, harvested a lot. In fact, I was in the first company has been exposed to EDI, we used EDI to achieve the main order data transmission, the customer issued purchase orders to us, through the VPN and FTP tools to the purchase order by the agreed message form to the designated file server, and then we EDI system will periodically go to the file server to get the message, Finally, parse and generate our sales order. These years have passed, I still remember that the most used is EDI850, EDI855.

First, introduce the concept of EDI

Electronic data interchange, EDI.

EDI is actually the original paper orders/delivery notices, such as business documents, from fax/courier and other traditional ways, into the online electronic data way to interact, thereby improving business efficiency. At the same time, through some EDI software implementation configuration, can often directly from the enterprise's business system to generate the corresponding document data, and automatically sent to the customer/supplier, to achieve application to application effect, to avoid the paper documents in human error (such as data errors, etc.). So big IT systems are more like EDI because EDI is transparent to business people and business people operate their day-to-day business systems.

EDI relies on several parts:

1, EDI transmission routes, general EDI through the AS2 agreement, FTP/S, etc., can also be directly through the third party van (value-added network) service providers (this and we use the same mode of e-mail). Because it involves business information, transmission security requirements will be relatively high;

2, EDI standards, that is, the organization of business data, the most commonly used ANSI X12 and the United Nations and the European Union EDIFACT, of course, there are many other standards, as long as EDI both sides follow the same standards, can be a good EDI interaction;

3, the EDI Software (environment) at both ends, the general best way is by EDI software to automatically send and receive EDI messages (data files), and automatically integrated into the enterprise business system.

One of the transmission routes, we use FTP file transfer, here I mainly introduce how Java is the FTP tool for uploading and downloading files, here Our FTP server is the Linux operating system.

Second, Java Shelf Package reference

Which "Commons-net-1.4.1.jar", "Jakarta-oro-2.0.8.jar" click on the link can be directly downloaded, and to ensure that it can be used, we can safely download.

Third, file path
The client needs to upload the folder path "E:\edi\edi850", by default is to upload all files under this folder
FTP server-side upload path is "/home/test/edi850", if uploaded as a path, the FTP server will establish the corresponding path

Four, Java code
FTP Class

Package com.pcmall; 
 
public class Ftp { 
  private string ipaddr;//IP address 
  private Integer port;//port number 
  private string username;//user name 
   private string pwd;//password 
  private string path;//path public 
 
  string getipaddr () {return 
    ipaddr; 
  } 
 
  public void Setipaddr (String ipaddr) { 
    this.ipaddr = ipaddr; 
  } 
 
  Public Integer Getport () {return 
    port; 
  } 
 
  public void Setport (Integer port) { 
    this.port = port; 
  } 
 
  Public String GetUserName () {return 
    userName; 
  } 
 
  public void Setusername (String userName) { 
    this.username = userName; 
  } 
 
  Public String getpwd () {return 
    pwd; 
  } 
 
  public void SetPwd (String pwd) { 
    this.pwd = pwd; 
  } 
 
  Public String GetPath () {return 
    path; 
  } 
 
  public void SetPath (String path) { 
    This.path = path; 
  } 
} 

Ftputil class

Package com.pcmall; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
 
Import Java.io.OutputStream; 
Import org.apache.commons.net.ftp.FTPClient; 
Import Org.apache.commons.net.ftp.FTPFile; 
Import org.apache.commons.net.ftp.FTPReply; 
 
Import Org.apache.log4j.Logger; 
 
  public class Ftputil {private static Logger Logger = Logger.getlogger (Ftputil.class); 
 
  private static ftpclient ftp; /** * Get FTP connection * * @param f * @return * @throws Exception/public static Boolean connectftp (Ft 
    P f) throws Exception {ftp = new ftpclient (); 
    Boolean flag = false; 
    int reply; 
    if (f.getport () = = null) {Ftp.connect (F.getipaddr (), 21); 
    else {ftp.connect (f.getipaddr (), F.getport ()); 
    } ftp.login (F.getusername (), f.getpwd ()); 
    Ftp.setfiletype (Ftpclient.binary_file_type); 
    Reply = Ftp.getreplycode (); if (! Ftpreply.ispositivecompletion(reply)) 
      {Ftp.disconnect (); 
    return flag; 
    } ftp.changeworkingdirectory (F.getpath ()); 
    Flag = true; 
  return flag; 
      /** * Close FTP connection */public static void Closeftp () {if (FTP!= null && ftp.isconnected ()) { 
        try {ftp.logout (); 
      Ftp.disconnect (); 
      catch (IOException e) {e.printstacktrace ();  }}/** * FTP upload file * * @param f * @throws Exception/public static void upload (file 
      f) throws Exception {if (F.isdirectory ()) {ftp.makedirectory (F.getname ()); 
      Ftp.changeworkingdirectory (F.getname ()); 
      string[] files = f.list (); 
        for (String fstr:files) {file File1 = new file (F.getpath () + "/" + fstr); 
          if (File1.isdirectory ()) {upload (file1); 
        Ftp.changetoparentdirectory (); 
          else {file File2 = new file (F.getpath () + "/" + fstr); FileInputStream INPUT = new FileInputStream (file2); 
          Ftp.storefile (File2.getname (), input); 
        Input.close (); 
      }} else {file File2 = new file (F.getpath ()); 
      FileInputStream input = new FileInputStream (file2); 
      Ftp.storefile (File2.getname (), input); 
    Input.close (); 
   }/** * DOWNLOAD LINK configuration * * @param f * @param localbasedir * Local directory * @param remotebasedir * Remote directory * @throws Exception */public static void Startdown (FTP F, String Localbasedir, String Remo 
        Tebasedir) throws Exception {if (ftputil.connectftp (f)) {try {ftpfile[] files = null; 
        Boolean changedir = Ftp.changeworkingdirectory (Remotebasedir); 
          if (Changedir) {ftp.setcontrolencoding ("GBK"); 
          Files = Ftp.listfiles (); for (int i = 0; i < files.length i++) {try {downloadFile (files[i), Localbasedir, Remoteb 
       ASEDIR);     catch (Exception e) {logger.error (e); 
            Logger.error ("<" + files[i].getname () + "> Download Failed"); 
        catch (Exception e) {logger.error (e); 
      Logger.error ("Exception occurred during download"); } else {Logger.error (link failed!) 
    "); /** * * Download FTP file when you need to download the ftp file, call this method according to the <b> obtained file name, local address, remote address </b> download * * @param ft PFile * @param relativelocalpath * @param relativeremotepath/private static void DownloadFile (ftpfile ft PFile, String Relativelocalpath, String relativeremotepath) {if (Ftpfile.isfile ()) {if (Ftpfile.getna 
        Me (). IndexOf ("?") = = 1) {OutputStream outputstream = null; 
          try {file Locafile = new file (Relativelocalpath + ftpfile.getname ()); 
          To determine whether a file exists or not, it returns if (Locafile.exists ()) {return; else {outputstream = NEW FileOutputStream (Relativelocalpath + ftpfile.getname ()); 
            Ftp.retrievefile (Ftpfile.getname (), outputstream); 
            Outputstream.flush (); 
          Outputstream.close (); 
        The catch (Exception e) {logger.error (e); 
            Finally {try {if (OutputStream!= null) {outputstream.close (); 
          The catch (IOException e) {logger.error ("Output file stream exception"); 
      }} else {String Newlocalrelatepath = Relativelocalpath + ftpfile.getname (); 
      String newremote = new String (Relativeremotepath + ftpfile.getname (). toString ()); 
      File FL = new file (Newlocalrelatepath); 
      if (!fl.exists ()) {fl.mkdirs (); 
        try {newlocalrelatepath = Newlocalrelatepath + '/'; 
        Newremote = Newremote + "/"; 
        String Currentworkdir = Ftpfile.getname (). toString (); BooleAn changedir = Ftp.changeworkingdirectory (Currentworkdir); 
          if (Changedir) {ftpfile[] files = null; 
          Files = Ftp.listfiles (); 
          for (int i = 0; i < files.length i++) {downloadFile (files[i), Newlocalrelatepath, newremote); 
        } if (Changedir) {ftp.changetoparentdirectory (); 
      The catch (Exception e) {logger.error (e); 
    }} public static void Main (string[] args) throws Exception {FTP FTP = new FTP (); 
    FTP.SETIPADDR ("192.168.16.128"); 
    Ftp.setusername ("test"); 
    Ftp.setpwd ("123456"); 
    FTPUTIL.CONNECTFTP (FTP); File File = new file ("e:/edi/edi850/");//If it is the path will upload all the files under the path, if it is a file upload the file ftputil.upload (file);//Upload files to FTP Ftputi L.startdown (FTP, "e:/ftptest/", "/home/test/edi850")//download FTP file test, the second parameter for the client to download the address, the third parameter for the file server download path System.out.println 
 
  ("OK"); 
 } 
 
}

After successful upload, FTP file Server files are as follows

After the download is successful, the client file is as follows
When opened, the contents of the file are as follows
Okay, EDI in the FTP tool to upload and download files first introduced here, the above code per person test, you can run.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.