The implementation of File splitter

Source: Internet
Author: User

Remember to read high school especially like reading ebook, but then still 2010, the economic conditions are not good, can not afford smart phones, only use some shanzhai machine, poor hardware facilities, the TXT text reader can only read the size of not more than 5M ebook, but the online e-book is basically more than 5M, In order to read these books, only on the Internet to download a TXT file splitter, split into small files, then downloaded to the phone, then did not understand programming, I think this divider is a very magical thing. However, now that you have learned the programming, it is very easy to realize a file splitter.

Now the author of Java in the IO stream knowledge, the realization of a file splitter, of course, the knowledge to achieve the core code, no interface, after all, in the Java Swing package made out of the interface is not so good-looking, the author of this piece of knowledge has not in-depth study.

To partition a file, first of all to know the size of the file into a number of blocks (or divided into several pieces, the author here only for the size of each block for example), for example, we want a size of 324 bytes of a file divided into 100 bytes each size of small files, then you need to divide the file into four pieces, and the actual size of the last piece is 24. Of course this is the case, the file is 324 bytes, and to split the file into 400-byte chunks, the actual size of the block is 324.


After splitting the file into chunks, we then need to write each piece out to disk. First we have to use Randomaccessfile to read the file into memory, use the Seek method to set where to start reading, and then use FileOutputStream to write out the read to disk. However, when writing, you will encounter a problem: the length of each read Len may be greater than the actual size of each piece (for example, the actual size of the block is 100, and Len is 120, this time it is not possible to read the contents of all written out), so you need to judge, you can see the following code in the comments.


The specific code is as follows:

Package Com.tiantang.split;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.FileOutputStream ; Import Java.io.ioexception;import Java.io.outputstream;import java.io.randomaccessfile;import java.util.ArrayList ; Import Java.util.list;public class Splitfile {//The path of the split file private String srcpath;//The file object being split private files src;// Split block number private int size;//the size of each block private long blocksize;//the actual size of each block private long actualblocksize;//the length of the original file private long length;//the collection of file names to be split private list<string> splitfilenames=new arraylist<string> ();p ublic splitfile ( String Srcpath,long blockSize) {this.srcpath=srcpath;this.blocksize=blocksize;init ();} /** * Initialization file delimited required parameter */private void init () {//path is empty, then throws exception if (Srcpath==null) {throw new RuntimeException ("File path is illegal");} Src=new file (srcpath);//Whether there is an if (!src.exists ()) {throw new RuntimeException ("file does not exist");} is the folder if (Src.isdirectory ()) {throw new RuntimeException ("Cannot split folder");} If the file exists length=src.length (); if (length<this.blocksize) {this.blocksize=length;} Calculate the number of blocks divided by size= (int) ((length-1)/this.blocksize+1);//Initialize the split file name Collection Initsplitfilenames ();} /** * Initial file is split after the name of the new generated file * Format: The original file name + number of blocks + extension */private void Initsplitfilenames () {//File full name (including suffix) String filename= Src.getname ();//Get the file's extension before the delimiter '. ' int Index=filename.indexof ('. '); /filename prefix string prefixname=filename.substring (0,index);//filename suffix string extname=filename.substring (index); for (int i=0 ; i<size;i++) {Splitfilenames.add (prefixname+ (i+1) +extname);}} /** * File segmentation details */public void split () {Randomaccessfile raf=null;outputstream os=null;try {raf=new randomaccessfile (src, "R"); byte[] b=new byte[1024];int len=0;for (int i=0;i<size;i++) {raf.seek (blocksize*i);//Calculate the actual size of the last piece if (i== (size-1 ) {actualblocksize=length-blocksize* (size-1);} Else{actualblocksize=blocksize;} Os=new Bufferedoutputstream (New FileOutputStream (New File (Src.getparent (), Splitfilenames.get (i))), while ( -1!= (len =raf.read (b))) {//If the length of the read has exceeded the actual length, only the actual length of the data will be written if (len>=actualblocksize) {os.write (b, 0, (int) actualblocksize) ; Os.flush (); break;} Else{os.write (b, 0, Len); Os.flush (); actualblocksize-=len;}}} catch (Exception e) {e.printstacktrace ();} Finally{if (os!=null) {try {os.close ();} catch (IOException e) {e.printstacktrace ()}} if (raf!=null) {try {raf.close ();} catch (IOException e) {e.printstacktrace ()}}}} Test public static void main (string[] args) {splitfile sf=new splitfile ("F:\\test\\tiantang\\java1\\testexception.java Sf.split ();}}
In this way we realize the segmentation of the file, and the idea of merging the files is to read the file into memory sequentially, then write the file out using new FileOutputStream (destpath,true), noting that the second parameter of the object needs to be specified as true, As long as this is to append the file to the write, otherwise it will be overwritten

The implementation of File splitter

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.