when importing an e-book, You need to copy the e-book from its original location to the library. In this process, you need to design a copy method, see the following Code :
Private Static void copyfile (string fromfile, string tofolder) throws ioexception {<br/> inputstream in = NULL; <br/> outputstream out = NULL; <br/> try {<br/> file targetfolder = new file (tofolder); <br/> If (! Targetfolder. exists () {<br/> targetfolder. mkdirs (); <br/>}< br/> file from = new file (fromfile); <br/> file to = new file (tofolder, from. getname (); <br/> In = new fileinputstream (from); <br/> out = new fileoutputstream (); <br/> byte [] Buf = new byte [configuration. buffer_size]; <br/> int Len; <br/> while (LEN = in. read (BUF)> 0) {<br/> out. write (BUF, 0, Len); <br/>}< br/>} finally {<br/> ebookmgrutil. safelyclose (in); <br/> ebookmgrutil. safelyclose (out); <br/>}< br/>}
The implementation is based on the following considerations:
1. Try-catch-finally Principle
All important resources are closed in finally
2. Copy an object to a directory and use the same file.
3. reduce useless code. The stream will throw an ioexception when it is closed, but the processing is useless at this time. Therefore, the safelyclose overload method is used. See the following code:
Public static void safelyclose (inputstream is) {<br/> If (is! = NULL) {<br/> try {<br/> is. close (); <br/>}catch (ioexception ex) {<br/> ex. printstacktrace (); <br/>}< br/> Public static void safelyclose (outputstream OS) {<br/> If (OS! = NULL) {<br/> try {<br/> OS. flush (); <br/> OS. close (); <br/>}catch (ioexception ex) {<br/> ex. printstacktrace (); <br/>}< br/>}
4. To handle exceptions in a unified manner, this method does not use catch blocks.
The code itself is not necessary for optimization, and the most important impact on performance is:
Byte [] Buf = new byte [configuration. buffer_size];
That is to say, the size of the buffer used for file copying, see the followingArticle:
Http://www.xiguaforever.net/confluence/display/JPT/Java+File+IO+Analysis#JavaFileIOAnalysis-Conclusion
We can know that when the buffer zone is 64 KB, the e-book is copied (1 Mbit/s ~ 5 MB) Relatively best performance.