Simple Java Breakpoint Continuation implementation principle _java

Source: Internet
Author: User
Tags readfile

Principle Analysis

In the development, "the breakpoint continues to pass" this kind of function is very practical and is common, sounds also has "the force lattice" the feeling. So usually we are interested in studying how this function is achieved?
In Java, there is also a lot of data on the web to achieve similar functions. However, most of them are to take a demo and then post the source code, the actual principle of its implementation has a detailed description of very few.
So we are in the initial contact, it is likely to be directly CRTL + c/v code, and then pounded the drum, but ultimately can also get the effect out. But it's obviously good and bad to do it in the beginner's way.
The advantage is that a lot of source code, the explanation is very small, if we are willing to work hard, in the code that others posted to the things that they do not understand what they look for information, to delve into. In the end, most of the harvest is plentiful.
The disadvantage is also very obvious: as a beginner, in the face of a large number of source code, feeling a lot of things are unfamiliar, it is easy to be intimidated. Even if the usage is understood in the end, it does not necessarily understand the principle of implementation.

Let's take a look at the basics today to see if the so-called "breakpoint continuation" is really such a "high Force".
In fact, in contact with a new "thing", it will be developed into some of our own more familiar things, to reference and contrast learning. It usually gets twice as effective.
If we have just come into contact with the concept of "breakpoint continuation", it is certainly hard to say 123. Then, "Play the game" we certainly will not unfamiliar.

OK, let's assume that we now have a "custom-made RPG game." Think about what we usually do when we play this kind of game?
Obviously, the first day we fought and killed the quartet, assuming finally came to the fourth pass. Although the fierce fighting, but a look at the clock on the wall, it is 12 o'clock in the morning, it is time to sleep.
This time is very awkward, in order to be able to play in the next time, the smooth convergence of our game progress, we should do?
Very simply, we don't turn off the game, go straight to sleep, and then play again the next day. That's OK, but it always seems to feel like there's something wrong with them.
So, this time, if this game has a function called "archive", it is very important. We select the archive directly, enter the archive name "four off", and then we can close the game.
Wait until the next game, we go directly to the "four" of the archive, and then read the file, you can continue to play the game.

At this time, the so-called "break-through" is very well understood. Let's take a look at the idea of "playing the game" before us:
Suppose that there is a file we need to download, when we downloaded a part of the situation, such as: Computer crash, no electricity, network interruption and so on.
In fact, it is like we play games before playing, suddenly 12 points need to go to bed and rest is a truth. OK, so this time the situation is:

If the game cannot be archived, then it means that the next time we play, the progress of the 4-pass will be lost and cannot be picked up.
corresponding, if the "download" behavior can not record a progress of this download. So, when we download the file again, we have to start over.
Words to here, in fact, we have found that for us the above mentioned behavior, the key lies in a word " continued "!
And we want to achieve the purpose of letting a disconnected behavior "continue", the key is to have "media" can record and read behavior "interrupt" The information of this node.

Translating into the world of programming

In fact, this is the most basic principle of "breakpoint continuation", which is vernacular: we want to record the interrupted location information when the download behavior is interrupted, and then read it in the next behavior.
With this location information, think about what we should do. Yes, it's easy to start downloading content directly from this location at the beginning of the new download behavior, instead of starting from scratch.
OK, we used vernacular to pull off the principle of so long, began to feel bored. So let's conclude by now and see how we can transform the principles into the programming world.

when the "Upload (download)" Behavior is interrupted, we need to record the location of this upload (download) (position).
when the "continuation" of this behavior begins, we jump directly to the postion to continue to upload (download) behavior.

Obviously the crux of the problem lies in the so-called "position", in our "Clearance game", you can use the "first few off" as the position unit.
So what do we use to measure "position" when it comes to the so-called "breakpoint continuation"? Obviously, the return of binary, because the essence of this is nothing more than the reading and writing of documents.

Then the rest of the work is very simple, first record position, which seems to have nothing to say, because it is only the persistence of data (memory, file, database), we have many ways.

Another key is that when the "continuation" behavior begins, we need to start reading and writing from the position position of the last record, so we need something similar to the "pointer" function.
We can certainly find a way to implement such a "pointer," but happily, Java has provided us with a class that is randomaccessfile.
The function of this class from the name is very intuitive embodiment, can be random to access the file. Let's take a look at the description of the class in the API documentation:

Instances of this class support read and write to random-access files. Random access to a file behaves like a large byte array stored in the file system.

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.

After reading the API instructions, we laughed, yes, isn't that what we want? Well, have we sharpened our knives for so long that we don't chop wood?

Example Demo

Since it's a "break-through" file, it's obvious that we're going to get a file. Maybe audio files, image files or something will look a bit more upscale.
But we have said that in the eyes of the big computer Brothers, they will eventually return to the binary. So here we create a simple "txt" file, because txt is more conducive to understanding.

We created a file named "Test.txt" in the root directory of D disk, and the contents of the file are simple, as shown in the figure:


Yes, we are typing in a simple 6 English letters. And then we right → Properties:


We see that the file size is now 6 bytes. This is why we say that all things to the end is inseparable from the "binary."
Yes, we all understand, because we entered 6 English letters, and 1 English letters will occupy the storage space is 1 bytes (that is, 8 bits).
So far, what we've seen is boring, because it's basically nonsense, and people with a little computer knowledge know it. Don't worry, we'll go on.

It is easy to read and write a file in Java. Suppose the current requirement is "write this file in D disk to E disk", then we will lift the keyboard, PA, and get it!
But in fact, the so-called "upload (download)" Of the file is not a little different? The difference is simply that the behavior is changed from "Just between native" to "native to server" file reading and writing.
At this point we would say, "Don't push it, these people know, ' The breakpoint continues '?" "In fact, here has been very simple, we again clear, the breakpoint to do is to do nothing more than:
Previous read and write behavior if there is an interruption, please record the contents of the file read and write the location information, when the "resume start" then directly move the pointer here, start continue reading and writing operations.

Repeated emphasis on the principle, in fact, because as long as you understand the principle, the rest is just the moves. This is just like the "Jiujiuguiyi" Dafa in Wuxia novels, the highest state is the return to Origin.
Any complex thing, as long as it understands its principles, we can peel it off and revert to something simple. By the same token, a series of simple things, logically combined, form a complex thing.

Below, we will immediately return to chaos, in the most basic form of the simulation of a "breakpoint continued transmission." Here we do not even write the code of the server, directly through a local test class to fix.
The effect we're going to achieve is simple: write the "test.txt" file in the D disk to the E disk, but midway through we'll simulate an "interrupt" behavior, and then resume the upload and finally complete the process.
In other words, we will see "D" as a computer and direct "e-disk" as a server. So we're not even going to have a half-dime relationship with the HTTP protocol, (of course, we certainly have to be involved in the ^<^), so we only care about the basic document read and write "broken" and "continued" principle is what.

In order to deepen understanding through contrast, we first write a normal code, that is, normal reading and writing, do not interrupt:

public class Test {public

 static void Main (string[] args) {
  //source file with target file
  sourcefile = new File ("d:/", "Te St.txt ");
  File TargetFile = new file ("e:/", "test.txt");
  Input output stream
  FileInputStream fis = null;
  FileOutputStream fos = null;
  Data buffer
  byte[] buf = new byte[1];

  try {
   fis = new FileInputStream (sourcefile);
   FOS = new FileOutputStream (targetfile);
   Data read/write while
   (Fis.read (BUF)!=-1) {
    System.out.println ("Write Data ...");
    Fos.write (BUF);
   }
  catch (FileNotFoundException e) {
   System.out.println ("Specify file does not exist");
  \ catch (IOException e) {
   //TODO: Handle Exception
  } finally {
   try {
    //Turn off input output stream
    if (FIS!= null)
     fis.close ();

    if (FOS!= null)
     fos.close ();
   } catch (IOException e) {
    e.printstacktrace ();
   }
}}}

This code runs, we will find in E disk has successfully copied a copy of "Test.txt." This code is simple, the only thing to say is:
We see that we're going to buf that the size of the buffer setting is 1, which actually means that every time we read, it reads one byte of data (that is, 1 English letters).

Now we're going to simulate this read and write interrupt behavior, and we'll refine the previous code as follows:

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Java.io.RandomAccessFile;

 public class Test {private static int position =-1;
  public static void Main (string[] args) {//source file with target file SourceFile = new file ("d:/", "test.txt");
  File TargetFile = new file ("e:/", "test.txt");
  Input output stream FileInputStream FIS = null;
  FileOutputStream fos = null;

  Data buffer byte[] buf = new Byte[1];
   try {fis = new FileInputStream (sourcefile);
   FOS = new FileOutputStream (targetfile);
    Data read/write while (Fis.read (BUF)!=-1) {fos.write (BUF);
     When the 3-byte file content has been uploaded, the network is interrupted, throwing an exception if (targetfile.length () = = 3) {position = 3;
    throw new Fileaccessexception ();
  A catch (Fileaccessexception e) {keepgoing (sourcefile,targetfile, position);
  catch (FileNotFoundException e) {System.out.println ("Specify file does not exist"); catch (IOException e) {//TODO:Handle exception} finally {try {//Turn off input output stream if (FIS!= null) fis.close ();
   if (FOS!= null) fos.close ();
   catch (IOException e) {e.printstacktrace ();
  }} private static void Keepgoing (File source,file target, int position) {try {thread.sleep (10000);
  catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
   try {randomaccessfile readFile = new Randomaccessfile (source, rw);
   Randomaccessfile WriteFile = new Randomaccessfile (target, rw);
   Readfile.seek (position);

   Writefile.seek (position);
   Data buffer byte[] buf = new Byte[1];
   Data read/write while (Readfile.read (BUF)!=-1) {writefile.write (BUF);
  The catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
  catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

 }} class Fileaccessexception extends Exception {}

To sum up, what we have done in this change:

First, we define a variable position, which records where the read and write is completed when the interrupt occurs. (This is for convenience, in practice it should be said that the value is persisted to the file or database, etc.)
then in the while loop where the file reads and writes, we simulate the occurrence of an interrupt behavior. This is when the TargetFile file length is 3 bytes and the simulation throws a custom exception. (We can imagine that the actual download has already uploaded (downloaded) the "x" Byte of content, this time the network is interrupted, then we will be in the network interrupt thrown in the exception of the "X" record).
The rest is as we said before, after the "continuation" behavior begins, wrapping our file through the Randomaccessfile class, and then assigning the pointer to the location where the interrupt occurred before using seek to get it done.
(The actual file download upload, we certainly need to save the interrupt value to the server, this way is usually Httpconnection.setrequestproperty ("RANGE", "bytes=x");

In our code, we turn on the "continuation" behavior, the Keepgoing method: We start to let the thread sleep for 10 seconds, which is exactly what we're doing to get the program to see the effect.
Now we run the program, then the file will open "from D disk to E-disk process", we first click on e-Disk, we will find that there is indeed a test.txt file, open it to find the following content:


Yes, this time we found that the content is only "abc". This is in our expectation, as our program simulation interrupts when the file uploads 3 bytes.

Ok, we silently wait for 10 seconds to pass and then click on the file to see if it will succeed:

Through the screenshot we found that the content has indeed become "ABC", which completes the continuation of the transmission.

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.