Large file segmentation, sorting, merging with Java

Source: Internet
Author: User

Import Java.io.BufferedReader;  import Java.io.BufferedWriter;  import java.io.FileNotFoundException;  import Java.io.FileReader;  import Java.io.FileWriter;  import java.io.IOException;  import java.util.Collections;  import Java.util.Iterator;  import java.util.LinkedList;  import Java.util.Random;    public class Largemappedfiles {    /**       * Big Data sort merge         *        * @param args       */      pub Lic static void Main (string[] args) throws IOException {      //write file path        String FilePath = "d:\\456";       //segmentation file path        String sqlitfilepath = "d:\\456\\123";       //number of data        int countnumbers=10000000;               //Sub-file number &NBsp;      int countfile=10;               //precision        int Countaccuracy=30*countfil E                long startnumber=system.currenttimemillis ();       //write Big Data files        WriteData (filepath,countnumbers);        SYSTEM.OUT.PRINTLN ("Storage Complete");               //split big data files into another 10 small files        Sqlitfiledat E (FilePath, sqlitfilepath,countfile);        SYSTEM.OUT.PRINTLN ("The file is cut! ");       //sorting the data of each file        Singlefiledatasort (sqlitfilepath,countfile);        SYSTEM.OUT.PRINTLN ("Each sub-file is sorted! ");               //precision adjustment, 10 file data for comparison integration        Deathdatafile (Filepath,sqlitfilepath,countaccuracy,countfile);        SYSTEM.OUT.PRINTLN ("Integration complete");        Long stopnumber=system.currenttimemillis ();        SYSTEM.OUT.PRINTLN ("Time consuming" + (Stopnumber-startnumber)/1000+ "milliseconds");       }       //write Big Data file       public static void WriteData (St Ring Path,int countnumbers) throws IOException {       Path = path + "\\12114.txt";    &nbs P   FileWriter fs = new FileWriter (path);        BufferedWriter fw=new bufferedwriter (FS);        for (int i = 0; i < countnumbers; i++) {        fw.write (new Rando M (). Nextint (integer.max_value) + "\ r \ n");       }        fw.close ();        Fs.close ();               }       //slicing big data files into another 10 small files        public static void SqlitfiledatE (String filepath, String sqlitpath,         int countfile) throws IOException {   &NB Sp   FileWriter fs = null;        BufferedWriter fw=null;        FileReader fr = new FileReader (filepath + "\\12114.txt");        BufferedReader br = new BufferedReader (FR); Read get whole row data                int i = 1;        LinkedList writerlists=new LinkedList ();    //initialize a collection of file stream objects        LinkedList fwlists=new LinkedList ();        for (int j = 1; J <= Countfile; j + +) {                 //Declaration object          FS = new FileWriter (Sqlitpath + "\\12" + j + ". txt", false);          fw=new bufferedwriter (FS);                             //loading objects into collections          Writerlists.add (FS);          Fwlists.add (FW);       }       //Determine if there is data return in the file stream        while (Br.ready ()) {                  int count=1;//initialize first file stream        &NBSP ; for (Iterator Iterator = Fwlists.iterator (); Iterator.hasnext ();) {         BufferedWriter type = (bufferedwriter) iterator.next (),        &NB Sp if (i==count)//judgment turn to the first few file streams write data          {          //write data, jump out, Make the next file stream, write the next data           type.write (Br.readline () + "\ r \ n");           break;         }          count++;         }         //determine if the last file stream was reached  &nbsP      if (i >= countfile) {         i = 1;         } E LSE          i++;       }        br.close ();        Fr.close ();        for (Iterator Iterator = Fwlists.iterator (); Iterator.hasnext ();) {        bufferedwriter object = (bufferedwriter) iterator.next ();        &N Bsp;object.close ();       }       //Traversal close all sub-file streams        for (Iterator Iterator = W Riterlists.iterator (); Iterator.hasnext ();) {        filewriter object = (FileWriter) iterator.next ();         obje Ct.close ();       }       }       //sort the data for each file      &NB Sp;public static void Singlefiledatasort (String path1,int countfile) Throws IOException {       LinkedList nums = null,        for (int i = 1; i < = Countfile; i++) {        nums = new LinkedList (),         string path = path1 + "\ \12 "+ i +". txt ";         try {         FileReader fr = new FileReader (path);  &nbsp ;       BufferedReader br = new BufferedReader (FR);          while (Br.ready ()) {          //Add a single data read into the collection &NBSP;&N Bsp        nums.add (Integer.parseint (Br.readline ()));         }         //Sort the collection          Collect Ions.sort (Nums);         //write sorted data to source file          Numbersort (nums, path);          br.close ();          fr.close ();         } catch (NumberFormatException e) {         E.printstacktrace ( );         } catch (FileNotFoundException e) {         E.printstacktrace () ;         } catch (IOException e) {         e.printstacktrace ()  &n Bsp     &NBSP,}       }       }       //sort each file data and write into source file       public static void Numbersort (LinkedList list, String path) {       TR Y {        filewriter fs = new FileWriter (path);         bufferedwriter Fw=new BufferedWriter (FS);         for (Iterator Iterator = List.iterator (); Iterator.hasnext ();) {         Object object = (object) iterator.next (),          Fw.write (o Bject + "\r\n ");         }         fw.close ();         fs.close ();       } catch (IOException e) {        e.printstacktrace ();    &N Bsp  }       }       //file Data final integration (precision Adjustment)       public Static V OID Deathdatafile (string filepath, String sqlitFilePath1,         int countaccuracy, int Countfi Le) throws IOException {       LinkedList nums = new LinkedList ();                                      //Add data to sort  &nbsp ;     Object temp = null;                          ,         &NB Sp                  //record the last number remaining in each order        Boolean ispass = false;        LinkedList ispasses = null;                          ,         &NB Sp          //Record data file status information        FileWriter fs = new FileWriter (filepath + "\\s Ort.txt ", false);          //create file streams so that consolidated data is written to        BufferedWriter bw=new bufferedwriter (FS);        FileReader fr = null;                          ,         &NB Sp                //statement read file stream        BufferedReader br = null;                          ,         &NB Sp            //Statement BufferedReader        LinkedList writerlists = new LinkedList (); Initialize the file Stream object collection        LinkedList writerlistfile = new LinkedList ();        for (int j = 1; J <= Countfile; j + +) {        //Declare object, open all sub-file streams to access all Sub-file Data        &NBSP;FR = new FileReader (sqlitFilePath1 + "\\12" + j + ". txt");                  //Open all BufferedReader for the next full line of reading      & nbsp &NBSP;BR = new BufferedReader (FR);                  //all FileReader objects into the collection        &NBS P Writerlistfile.add (FR);                  //all BufferedReader objects into the collection         writerlists.add (BR);       }        for (;;) {        //storing data for 10 source files in the collection for later decision         ispasses = new Linkedli St ();  &nBsp               //individual data from 10 source files         for (Iterator ite Rator = Writerlists.iterator (); Iterator.hasnext ();) {         BufferedReader object = (BufferedReader) iterator.next ();        & nbsp Object obj = null;          while (Object.ready ()) {          //add data for every file stream  & nbsp        nums.add (Integer.parseint (Object.readline (). toString ()));           break;         }          if (object.ready () = = False)      &NB Sp    ispasses.add ("true");          //Set the data status in each file into the collection         }                  //decision is the first time to come in         if (nums.size ()% Countaccuracy = = 0 & & ispass = = False) {        //Sort the collection          Collections.sort (nums); &n bsp;       //Receive maximum data, other data written to total sort file          temp = numbersortdata (nums, file Path, FALSE, countaccuracy, BW);                   //Reinitialize set          Nums = new LinkedList ();         //Add previous group to compare the remaining data          Nums.add (temp);          Ispass = true;         //record the amount of data in the source file for the next iteration of          continue;         }         if (ispass) {         if (nu Ms.size ()% countaccuracy = = 1 && nums.size () > 1) {          //sorting collections  & nbsp        collections.sort (nums);        &NBSp  //receives the largest data, other data is written to the total sort file           temp = Numbersortdata (Nums, filepath, True, COUNTAC Curacy,            &NBSP;BW);           nums = new LinkedList ();           nums.add (temp);           continue;         }         }         //record the location of the next set of data &nbs p;       //determine if 10 files are not data         if (ispasses.size () = = Countfile) {          Collections.sort (nums);          temp = Numbersortdata (Nums, filepath, true, countaccuracy, BW);          nums = new LinkedList ();          break;         }       }        bw.close ();       //close write stream        Fs.close ();               //Close all BufferedReader        for (Iterato R iterator = Writerlists.iterator (); Iterator.hasnext ();) {        bufferedreader object2 = (BufferedReader) iterator.next ();        & Nbsp;object2.close ();       }               //Close all FileReader    &N Bsp   for (Iterator Iterator = Writerlistfile.iterator (); Iterator.hasnext ();) {        filereader object = (FileReader) iterator.next ();         obje Ct.close ();       }       }       //Sorting the data, writing to the final file (precision Adjustment)    & nbsp  public static Object numbersortdata (LinkedList list, String FilePath,         boolean ISPA SS, int Countaccuracy,bufferedwriter FS) {   &nbsP   Object temp = 0;                          ,         &NB Sp                    //record last value        int tempcount = 0;                          ,         &NB Sp                  //record-written data location        try {   &N Bsp    for (Iterator Iterator = List.iterator (); Iterator.hasnext ();) {         Object object = (object) iterator.next (),         //judge whether it is the last A number          if (Tempcount = = List.size ()-1) {          //judgment set Less than 100 numbers           if (List.size () < Countaccuracy + 1 && ispass) {           temp = null;           } else {           TEMP = object;    &nbs P       break;           }  www.2cto.com       }        &NBSP ; Write to data source          Fs.write (object + "\ r \ n");         //Record data subscript          tempcount++;         }       } catch (IOException e) {        e . Printstacktrace ();       }        return temp;       }  }  

Using Java for large file segmentation, sorting, merging

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.