Java Breakpoint Continuation Implementation principle is very simple

Source: Internet
Author: User
Tags readfile

Principle Analysis

In the development, "breakpoint continuation" This function is very practical and common, it sounds like a "forced lattice" feeling. So usually we are interested in studying how this function is implemented?
In Java, you can find a lot of information on how to implement similar functions on the web. However, most of them are to give a demo and then put out the source code, the actual implementation of the principle of the detailed instructions are very few.
So when we first approached, it was likely to be a direct CRTL + c/v code, and then beat the drums, but eventually we could get the results out. But this is obviously a good and bad thing to do when you are a beginner.
The advantage is that there are a lot of source code, very few explanations, and if we work hard, we will look at the data and delve into what others have not understood. In the end, most of the harvest will be fruitful.
The disadvantage is also obvious: as a beginner, face a lot of source code, feel a lot of things are very unfamiliar, it is easy to be intimidated. Even if you finally get a general idea of how to use it, you don't necessarily understand the implementation principle.

Today we will go from the most basic point of view, to see what the so-called "continuation of the breakpoint" this thing is not really so "high-force lattice."
In fact, in contact with a new "thing", it is to be made into some of our own more familiar things, to reference and contrast learning. Usually do more with less.
If we had just touched on the concept of "breakpoint continuation", it would be hard to say clearly 123. Then, "Play the game" we certainly will not be unfamiliar.

OK, so let's say we now have a "customs-based RPG". 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. Although the battle is raging, but a look at the wall clock, already 12 o'clock in the morning, it is time to sleep.
This time is very embarrassing, in order to be able to play in the next time, the smooth integration of the progress of our game, we should do?
Very simple, we do not turn off the game, go straight to sleep, the next day to play again. This is possible, but it seems that there is always something unpleasant.
Well, at this point, if the game has a feature called "Archive", it's critical. We select the archive directly, enter the archive name "four off", then you can close the game.
When the next game, we directly find the "four-off" this archive, and then read the document, you can then play the game.

At this time, the so-called "continuation of the breakpoint" is very well understood. Let's take a look at our previous "Play games" mentality:
Suppose, now there is a file that we need to download, when we download a part of the time, there is a situation, such as: computer crashes, no power, network interruption and so on.
In fact, this is like playing games before we play, suddenly 12 points need to go to sleep rest is a reason. OK, so this time the situation is:

  • If the game can not be archived, then it means that the next time we play, the progress of the 4-level pass will be lost, unable to access the file.
  • Corresponding, if the "download" behavior cannot record a progress of this download. Then, when we download the file again, we can only start over.

Word here, in fact, we have found that for our 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 the behavior of "break" this node information.

Transforming into the world of programming

In fact, this is the "continuation of the breakpoint" the most fundamental principle, with plain English said is: we want to be interrupted when the download behavior, record the location of the interrupt information, and then read 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.
Well, we used plain English to rip off the principle of so long, and began to feel bored. So let's wrap it up now and see how we can translate the principles into the programming world.

  • When the "upload (download) behavior" is interrupted, we need to record the location (position) of this upload (download).
  • When the "continued" behavior begins, we jump directly to postion to continue uploading (downloading) behavior.

Obviously the crux of the problem lies in the so-called "position", in our "Clearance game", you can use the "first few" as the unit of this position.
So what do we use to measure "position" when switching to so-called "breakpoint continuation"? Obviously, the regression binary, because the essence of this is nothing more than read and write files.

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 a lot of ways.

Another key is that when the "continuation" behavior starts, we need to start reading and writing from the last recorded position location, 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 such a class, that is Randomaccessfile.
This class of functions from the name of the very intuitive embodiment, to randomly 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 the random Access file is created in read/write mode, the output operation is also available, and the output operation starts writing bytes from the file pointer and moves the file pointer forward as it writes to the byte.

Writing an output operation after the current end of the suppressed array causes the array to expand. The file pointer can be read by the Getfilepointer method and set through the Seek method.

After reading the API instructions, we laughed, yes, isn't that what we want? Well, we've been sharpening our knives for so long, and we're not cutting wood?

Example Demo

Since it's a "breakpoint continuation" for a file, it's clear that we're going to get a file out first. Maybe the audio file, the image file or something will look a little bit more.
But as we have already said, in the eyes of the computer's big brothers, they will eventually return to "binary". So here we create a simple "txt" file, because TXT is better for understanding.

We create a file named "Test.txt" in the root directory of the D drive, the file content is very simple:

Yes, what we're typing is a simple 6 English alphabet. Then we right click → Properties:

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

It is easy to read and write a file in Java. If the demand now is "to write this file D to the E-disk," then we will bring up the keyboard, PA PA, take care of it!
But in fact, the so-called "upload (download)" is not a different? The difference is simply that the behavior is changed from "Just between this machine" to "native to server" file read and write.
At this point we will say, "Do not force, these people know, ' the breakpoint continued to pass ' it?" ", in fact, it has been very simple here, we once again clear that the breakpoint to continue to do is nothing more than:
If there is an interruption in the previous read and write behavior, please record the location information of the contents of this read-write file;

Repeated emphasis on the principle, in fact, as long as the understanding of the principle, the rest is only the moves. This is like the "Jiujiuguiyi" Dafa in the martial arts fiction, the Supreme realm is the return to the origin.
Any complex thing, as long as it understands its principles, we can peel it off and revert to something simple. In the same vein, a series of simple things, logically combined, form complex things.

Below, we will immediately return to chaos, in the most basic form to simulate a "breakpoint continuation." Here we do not even write the server code, directly through a local test class.
The effect we're going to make is simple: we'll write the "test.txt" file in the D-Drive to the e-drive, but halfway through we'll simulate an "interrupt" behavior, and then continue uploading again to finish the process.
In other words, we will treat "D" as a computer and direct "e-disk" as a single server. So we don't even have a half-penny relationship with the HTTP protocol, and (of course, we're definitely going to have to ^<^ with it), so we're only concerned with the basic principles of "break" and "continuation" of the document's reading and writing.

In order to deepen understanding through contrast, we first write a normal code, that is, normal read and write, no interruption:

 Public classTest { Public Static void Main(string[] args) {//source files and destination filesFile sourcefile =NewFile ("d:/","Test.txt"); File targetfile =NewFile ("e:/","Test.txt");//input/output streamFileInputStream FIS =NULL; FileOutputStream fos =NULL;//Data buffers        byte[] buf =New byte[1];Try{FIS =NewFileInputStream (sourcefile); FOS =NewFileOutputStream (targetfile);//Data read/write             while(Fis.read (BUF)! =-1) {System. out. println ("Write Data ...");            Fos.write (BUF); }        }Catch(FileNotFoundException e) {System. out. println ("The specified file does not exist"); }Catch(IOException e) {//Todo:handle exception}finally{Try{//Close the 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 the E-disk has been successfully copied a copy of the "Test.txt". This code is very simple, the only thing to say a little bit is:
We see that we will buf, that is, the size of the buffer set is 1, which in fact represents us every time read, is reading a byte of data (that is, 1 English letters).

Now, let's simulate the behavior of this read-write interrupt, 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 intPosition =-1; Public Static voidMain (string[] args) {//source files and destination filesFile sourcefile =NewFile ("d:/","Test.txt"); File targetfile =NewFile ("e:/","Test.txt");//input/output streamFileInputStream FIS =NULL; FileOutputStream fos =NULL;//Data buffers        byte[] buf =New byte[1];Try{FIS =NewFileInputStream (sourcefile); FOS =NewFileOutputStream (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 and an exception is thrown                if(targetfile.length () = =3) {position =3;Throw NewFileaccessexception (); }            }        }Catch(Fileaccessexception e)        {keepgoing (sourcefile,targetfile, position); }Catch(FileNotFoundException e) {System.out.println ("The specified file does not exist"); }Catch(IOException e) {//Todo:handle exception}finally{Try{//Close the input/output stream                if(FIS! =NULL) Fis.close ();if(Fos! =NULL) Fos.close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }Private Static voidKeepgoing (File source,file Target,intPosition) {Try{Thread.Sleep (10000); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Try{Randomaccessfile ReadFile =NewRandomaccessfile (Source,"RW"); Randomaccessfile WriteFile =NewRandomaccessfile (Target,"RW");            Readfile.seek (position); Writefile.seek (position);//Data buffers            byte[] buf =New byte[1];//Data read/write             while(Readfile.read (BUF)! =-1) {writefile.write (BUF); }        }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }} class fileaccessexception extends Exception {}

To summarize what we have done in this change:

  • First, we define a variable position, which records where the read and write is completed when an interrupt occurs. (This is for convenience, in fact it should be said that the value is stored in a file or database, etc. to be persisted)
  • Then in a while loop where the file reads and writes, we simulate the occurrence of an interrupt behavior. Here is when TargetFile's file length is 3 bytes then the simulation throws a custom exception for us. (We can imagine that in the actual download, the "x" bytes of content have been uploaded (downloaded), this time the network is interrupted, then we will be in the network interrupt thrown by the exception of the "X" recorded).
  • The rest is, as we said before, after the "continuation" behavior begins, we wrap our files through the Randomaccessfile class and then use seek to specify the pointer to the location where the previous break occurred before reading and writing.
    (The actual file download upload, we certainly need to save the interrupt value to the server, this method is usually httpconnection.setrequestproperty ("RANGE", "bytes=x");

In our code, we turn on the "continue" behavior, which is the Keepgoing method: We start to let the thread hibernate for 10 seconds, which is exactly what we want to run the program to see.
Now we run the program, then the file will open the "D disk upload to the E-disk process", we first open the E-disk, we will find that there is indeed a test.txt file, open it found the content as follows:

Yes, this time we found that the content only "ABC". This is within our expectation, because our program simulates an interrupt when the file uploads 3 bytes.

Ok, let's wait 10 seconds to go, then open the file and see if it will succeed:

Through our discovery, the content has indeed become "ABC", and thus the continuation of the transmission has been completed.

Java Breakpoint Continuation Implementation principle is very simple

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.