Java implementation of FTP batch large file upload download Chapter 2_java

Source: Internet
Author: User
Tags connect socket file upload flush socket file permissions ftp protocol

Then on a learning Java file upload download 1.

v. Continuous transmission of Breakpoints

For familiar with the QQ programmer, QQ breakpoint extension function should be very impressive. Because it is practical and very related. Therefore, in our uploading and downloading process, it is very important to realize the function of breaking point.

In fact, the principle of the continuation of the breakpoint is very simple, in the process of uploading, first go to the service to find, whether there is this file, if there are some files, compare the size of the file on the server and the size of the local file, if the file on the server is smaller than the local, it is believed that the file upload process should be able to carry out a breakpoint.

In the process of implementation, the Randomaccessfile class becomes useful. Instances of this class support reading and writing to random-access files. Random-access files behave like a large byte array stored in the file system. There is a cursor or index pointing to the suppressed array, called a file pointer, and the input operation reads the byte from the file pointer and moves the file pointer forward as the byte is read. If a random access file is created in read/write mode, the output operation is also available; the output operation writes bytes from the file pointer and moves the file pointer forward as the byte is written. The output operation after writing the current end of the suppressed array causes the array to expand. The file pointer can be read through the Getfilepointer method and set by the Seek method.

The Skipbytes method of the Randomaccessfile class attempts to skip the input n bytes to discard the skipped bytes. If the size of the file to be uploaded from the server is N, then the Skipbytes method can skip the n bytes, thus starting from the new place to start a breakpoint continued transmission. Specific method descriptions can be found in JDK5 API descriptions.

You can see the implementation of the upload download interrupt point in the Run method of the Net.sf.jftp.net. DataConnection class, the code is as follows:

public void Run () {try {newline = Con.getcrlf ();
          if (Settings.getftppasvmode ()) {try {sock = new Socket (host, Port);
        Sock.setsotimeout (Settings.getsockettimeout ());
          catch (Exception ex) {ok = false;
        Debug ("Can ' t open Socket on port" + port);
        } else {//log.debug ("trying New server socket:" +port);
        try {ssock = new ServerSocket (port);
          catch (Exception ex) {ok = false;
        Log.debug ("Can ' t open serversocket on port" + port);
    '} ' catch (Exception ex) {debug (ex.tostring ());

    } Isthere = true;

    Boolean OK = true;
    Randomaccessfile fout = null;
    Bufferedoutputstream bOut = null;

    Randomaccessfile fIn = null; try {if (!

        Settings.getftppasvmode ()) {int retry = 0; while ((retry++ < 5) && (sock = null)) {try {ssock.setsotimeout (settings.connectiontimeout)
            ;
          Sock = Ssock.accept ();
            catch (IOException e) {sock = null;

            Debug ("Got IOException while trying to open a socket!"); if (retry = = 5) {Debug ("Connection failed, tried 5 times-maybe try a higher timeout in Setting
            S.java ");

            } finished = true;
          Throw e;
          finally {ssock.close ();
        Debug ("Attempt timed out, retrying");
        } if (OK) {byte[] buf = new Byte[settings.buffersize];

        Start = System.currenttimemillis ();

        int buflen = 0;
          ---------------Download, download----------------------if (type.equals (get) | | type.equals (GETDIR)) {
    if (!juststream) {try {          if (resume) {file F = new file (file);
                Fout = new Randomaccessfile (file, "RW");
                Fout.skipbytes ((int) f.length ());
              Buflen = (int) f.length ();  } else {if (LocalFile = null) {LocalFile =
                File
                } File F2 = new file (Settings.apphomedir);

                F2.mkdirs ();

                File F = new file (LocalFile);
                if (f.exists ()) {f.delete (); } bOut = new Bufferedoutputstream (new FileOutputStream (LocalFile), settin
              Gs.buffersize);
              } catch (Exception ex) {debug ("Can ' t create outputfile:" + file);
              OK = false;
            Ex.printstacktrace (); }
          }

        
        //---------------Upload, Upload----------------------if (type.equals) | | type.equals (PUTDIR)) {if (in
              
              = = null) {try {fIn = new Randomaccessfile (file, ' R ');
              if (resume) {fin.skipbytes (Skiplen);
            }//fin = new Bufferedinputstream (new FileInputStream (file));
              catch (Exception ex) {debug ("Can" T open inputfile: "+" ("+ Ex +"));
            OK = false; } if (OK) {try {out = new Bufferedoutput
            Stream (Sock.getoutputstream ());
              catch (Exception ex) {ok = false;
            Debug ("Can ' t get OutputStream"); } if (OK) {try {int len = SKIplen;
                
                Char b;
                  
                  while (true) {int read;
                  if (in!= null) {read = In.read (BUF);
                  else {read = Fin.read (BUF);
                  
                  Len + = read;
                  System.out.println (file + "" + type+ "" + Len + "" + read);
                  if (read = = 1) {break; } if (newline!= null) {byte[] buf2 = modifypu
                    T (buf, read);
                  Out.write (buf2, 0, buf2.length);
                  else {out.write (buf, 0, read); } con.fireprogressupdate (file, type,Len);
                  if (time ()) {//Log.debugsize (Len, False, False, file);
                  } if (read = = streamtokenizer.tt_eof) {break;
                
                } out.flush ();
              Log.debugsize (Len, False, True, file);
                catch (IOException ex) {ok = false;
                Debug ("Error:data connection closed.");
                Con.fireprogressupdate (file, FAILED,-1);
              Ex.printstacktrace (); catch (IOException ex) {log.debug ("Can" T connect socket
      To ServerSocket ");
    Ex.printstacktrace ();
          Finally {try {if (out!= null) {Out.flush ();
        Out.close ();
 }     catch (Exception ex) {ex.printstacktrace ();
          try {if (BOut!= null) {Bout.flush ();
        Bout.close ();
      } catch (Exception ex) {ex.printstacktrace ();
        try {if (fout!= null) {fout.close ();
      } catch (Exception ex) {ex.printstacktrace ();
        try {if (in!= null &&!juststream) {in.close ();
        } if (fIn!= null) {fin.close ();
      } catch (Exception ex) {ex.printstacktrace ();
    } try {sock.close ();
    catch (Exception ex) {debug (ex.tostring ()); } if (!
      Settings.getftppasvmode ()) {try {ssock.close ();
      catch (Exception ex) {debug (ex.tostring ());} finished = true;
    if (OK) {con.fireprogressupdate (file, finished,-1);
    else {con.fireprogressupdate (file, FAILED,-1);

 }
  }

Six, FTP port mapping

FTP data connection has PASV and port two kinds, if your FTP server is located in the intranet, need to do port mapping. I just started with the FTP network outside the network mapping is not very understanding, so began to walk a lot of detours, began to think that it is their own procedures have problems, wasted a lot of time, hope that through this paragraph, so that everyone in the development of the time to spend less or not spend these unnecessary time and energy.

PCD has an article on a direct access to the Intranet method, in fact, we only use the port mapping tool, we can easily achieve the purpose of penetrating the intranet. The port mapper is a tool such as this, and it is worth mentioning that it is free from the command line mode and provides a graphical interface for the operating environment.

In order for you to understand better, first say the principle. Suppose there is now a LAN, host for A, LAN in addition to the host, there is a machine for the b,b machine, of course, through the host a Internet. There is also an Internet-accessible machine for C, which is not in a LAN with A and B. Normally, C machine can only access to a host, but not through the LAN, access to B. After the port mapping, when the C machine access to the designated port of host A, the "Port mapper" on host a functions, it will transfer the data on the specified port to a designated port on another machine in the LAN to achieve the purpose of accessing the Intranet machine. That said, everybody understand. As for the specific how to configure, I think it should not be a difficult thing, and, on the internet such a lot of graphics, please refer to the article on the network to set.

Of course, the advantages of achieving direct access to the intranet are obvious, otherwise, at least the FTP resources are fully utilized. However, it is important to remind readers that direct access to the intranet may threaten the security of the intranet. I believe that most of the friends of the importance of host security is still attached importance, but often ignore the intranet machine security settings. Once you have achieved direct access to the intranet, it must be treated like a host to the intranet machine, or your entire network will be at risk.

Accessing Client Resources

The security policy for the Java application environment, which is expressed by a policy object for the license of different resources owned by different code. In order for the applet (or an application running under SecurityManager) to perform protected behavior, such as reading and writing files, the applet (or Java application) must obtain permission for that operation, and the security policy file is used to implement these licenses.

The policy object may have multiple entities, although at any time only one function can occur. The currently installed policy object can be obtained either by calling the GetPolicy method in the program or by invoking the SetPolicy method. The policy object evaluates the entire policy, returning an appropriate permissions object detailing which resources the code can access. Policy files can be stored in unformatted ASCII files or in binary files or databases of policy classes. This article discusses only the form of unformatted ASCII files.

In practice, we don't need to manually write a java.policy file of that complexity, especially if you don't use a digital signature. At this time, we can learn from the JRE provided to our ready-made C:\Program files\java\jre1.5.0_12\lib\security\ Java.policy files, according to our needs to make the appropriate changes, this article on the use of digital signatures to write security policy files. Below, is a complete java.policy file that is used under Windows NT/XP. The purpose of each "permission" record is illustrated in the file, using the form of annotations, respectively. Of course, different programs may not have the same requirements for resource access, which can be adjusted and selected according to the needs of the project.

Grant {//access to System and user directory "read" Permission Java.util.PropertyPermission "User.dir", "read";  
    Permission Java.util.PropertyPermission "User.home", "read";  
    Permission Java.util.PropertyPermission "Java.home", "read";  
    Permission Java.util.PropertyPermission "Java.class.pat", "read";  
    Permission Java.util.PropertyPermission "User.Name", "read";  
    Operation permissions on threads and thread groups permission Java.lang.RuntimePermission "AccessClassInPackage.sun.misc";  
    Permission Java.lang.RuntimePermission "AccessClassInPackage.sun.audio";  
    Permission Java.lang.RuntimePermission "Modifythread";  
    Permission Java.lang.RuntimePermission "Modifythreadgroup";  
    Permission Java.lang.RuntimePermission "Loadlibrary.*";  
    Read and Write file permissions permission Java.io.FilePermission "<<all files>>", "read";  
    Permission Java.io.FilePermission "${user.dir}${/}jmf.log", "write"; Permission Java.io.FilePermission "${user.home}${/}. JmstudioCFG "," write ";  
    Permission Java.net.SocketPermissio "*", "connect,accept";  
    Permission Java.io.FilePermission "c:\winnt\temp\*", "write";  
    Permission Java.io.FilePermission "c:\winnt\temp\*", "delete";  
    Permission Java.awt.AWTPermission "Showwindowwithoutwarningbanner"; 

  Permission Javax.sound.sampled.AudioPermission "Record";  
    Operation socket port of various permissions permission Java.net.SocketPermission "-", "Listen";  
    Permission Java.net.SocketPermission "-", "accept";  
    Permission Java.net.SocketPermission "-", "Connect";  
    Permission Java.net.SocketPermission "-", "resolve";  
   Permission java.security.AllPermission;

  };  
    Grant Signedby "Saili" {permission Java.net.SocketPermission "*:1024-65535", "connect,accept,resolve";  
    Permission Java.net.SocketPermission "*:80", "Connect";  
    Permission Java.net.SocketPermission "-", "Listen, accept, connect, listen, resolve", signedby "ganja";Permission Java.net.SocketPermission "-", "accept";  
    Permission Java.net.SocketPermission "-", "Connect";  
    Permission Java.net.SocketPermission "-", "resolve";  
   Permission java.security.AllPermission;

 };

In this project, in order to use the client's user settings more convenient and simple, the above file using VB or C # to make a small program to write. Then the JRE and some exe together into an EXE package, when the JRE installation is completed, this small program is responsible for finding the JRE in the operating system installation path, and in the program write this java.policy file, overwriting the original file. As a result, the user simply installs an EXE file, simplifying the number of times the installation is installed.

Vii. Applet Callback Server

The ability to communicate between JavaScript and applets brings us a lot of convenience, and Java and JavaScript complement each other to develop more functional Web applications. b/s can make full use of the advantages of Java, to bring us more network experience, user-friendly. The author uses a lot of swing components developed by the application of the applet to achieve B/s architecture, so that can fully display the advantages of swing components, easy to upgrade the system, easy to maintain; and there is the web, sometimes the client to use local hardware resources, The author knows that through the applet to implement, through the applet to invoke JAVAAPI to achieve. How exactly do we see the communication between JavaScript and applets?

1.JavaScript Access Applet

<applet name= "Appletname" .../>//javascript Access applet properties.

Window.document.appletName.appletField (attribute must be public, "window.document.") You can also//javascript access to the applet method without writing it.

Window.document.appletName.appletMethod (method must be public, "window.document.") Or you can not write).

2.Applet access to JavaScript

Live Connect provides Java and JavaScript interfaces that allow JavaScript to be used in Java applet applets.

Need to use a jar package, in the C:\Program files\java\ directory to find, about 5M more, in fact, is open to see which has netscape.javascript.JSObject. If you don't have Netscape or you can do it from the Internet. You can rename it to Netscape.jar (not required) and be sure to add it to the classpath so that you can compile it when you develop it. It is particularly noted that deployment does not need to include Netscape.jar, as the entire package is downloaded to the client and affects speed.

 Introduction of Netscape
import netscape.javascript.JSObject; 
import netscape.javascript.JSException; You can allow exception events to be handled in small programs public
void Calljavascript (String callbackjavascript) {
  jsobject window = Jsobject.getwindow ( this); Gets the JavaScript window handle, referencing the current document window
  jsobject docment = (jsobject) window.getmember ("document");
    Form= (jsobject) doc.getmember ("Textform");//Access JavaScript Form Object 
    textfield= (jsobject) Form.getmember (" TextField "); Access JavaScript text Object 
     text= (String) textfield.getmember (" value ");//Get the value of the text area
  // Invoke JavaScript's alert () method
  //window.eval (alert (\ "This alert comes from java!\"));
  Window.call (callbackjavascript, NULL);//parameter is represented as an array.
  }

Eight, the operation effect

1. Upload

(1). Launch upload above


(2). Upload in


(3). Upload in


(4). Upload successful


2. Download

(1) Save path of download file


(2) in the download


(3) in the download


(4) Successful download


Ix. Summary

In this paper, the author will be in the actual project upload download problem solution is elaborated, through the use of FTP protocol, to achieve the bulk of the basic web of large files upload and download. At the same time through the applet technology implementation of the local resources on the client access. Some problems such as progress bar, extension of breakpoint, and mapping of FTP and intranet are discussed in this paper. This is the author based on some FTP Java client library based on the application. Hope to have certain reference function to the reader. To supplement some of the outstanding matters. There are also some easy and online descriptions or examples of content that are not listed here. such as FTP in the server-side Serv-u software How to build FTP services, applets in the JSP page embedded mode and parameter transfer method, in Eclipse or NetBeans to start the applet and so on, due to the limitations of space, there is no detailed description, Please refer to the online examples or other reference materials.

Download address :http://xiazai.jb51.net/201608/yuanma/FTPTransfer (jb51.net). rar

Note, considering the copyright problem, did not send the Java class file, but such a jar file how to restore to the Java file, I think we are very familiar with it, hehe.

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.

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.