Java ——— Reading and writing of large binary files

Source: Internet
Author: User

Because of the needs of the project, binary files need to be read and written, converted.

File Description: The binary files obtained by other programs, the contents of the file is: 23,543 triangles, 13,270 vertices of the triangular network corresponding to the 721 set of Velocity vector (U, v) files, in layman's words, a data contains two double-precision values, each set of arrays contains 23,543 data, In the case of a double value, there is a total of 23543 * 721 * 2 =33,949,006 data. The FORTRAN program stores a binary file with a numeric value of 8 bytes, and the final file size is as follows:

              

  

Test: After the data is read from the file, it is converted to decimal and stored in another file.

  

/*** For large file storage, please call Beginsave, Addsave, endsave in turn. *  * @authorCK **/ Public classdatautil {dataoutputstream binaryout=NULL; BufferedWriter TextOut=NULL; String FilePath=NULL; enumSavefiletype{text,binary};    Savefiletype Savefiletype; /*** Double Turn byte[] * *@paramd *@return     */     Public Static byte[] Double2bytes (Doubled) {LongValue =Double.doubletorawlongbits (d); byte[] Byteret =New byte[8];  for(inti = 0; I < 8; i++) {Byteret[i]= (byte) ((Value >> 8 * i) & 0xFF); }        returnByteret; }    /*** byte[] Turn double * *@paramarr *@return     */     Public Static DoubleBytes2double (byte[] arr) {        LongValue = 0;  for(inti = 0; I < 8; i++) {Value|= ((Long) (Arr[i] & 0xff)) << (8 *i); }        returndouble.longbitstodouble (value); }    /*** Start storage of large data storage *@paramFilePath File path *@paramsavefiletype saved file types, text files, double-precision binary files *@return     * @throwsIOException*/     Public BooleanBeginsave (String filepath,savefiletype savefiletype)throwsIOException {if(FilePath = = "" | | FilePath = =NULL) {System.out.println ("The Savepath is null."); return false; }         This. Filepath=FilePath;  This. Savefiletype=Savefiletype; File datafile=NewFile (FilePath); if(!Datafile.getparentfile (). exists ())        {Datafile.getparentfile (). Mkdirs (); }        if(Datafile.exists ()) {datafile.delete ();        } datafile.createnewfile (); Switch( This. Savefiletype) { CaseText:textout=NewBufferedWriter (NewFileWriter (DataFile,true));  Break;  CaseBinary:binaryout=NewDataOutputStream (NewFileOutputStream (DataFile,true));  Break; default:             Break; }                return true; }/*** Additional storage of large file storage *@paramDatastr If the text store is not required, if a double binary file, separated by several spaces *@return * @throwsIOException*/     Public BooleanAddsave (String datastr)throwsioexception{Switch( This. Savefiletype) { CaseText: This.            Textout.append (DATASTR);  Break;  CaseBinary:datastr=Datastr.trim (); String[] DataArray=datastr.split ("\\s+");  for(inti=0;i<dataarray.length;i++){                 This.            Binaryout.write (Double2bytes (double.parsedouble (dataarray[i))); }                                 Break; default:             Break; }                return true; }    /*** Save the end of large file storage, empty the cache, close the file. * @return     * @throwsIOException*/     Public BooleanEndsave ()throwsioexception{Switch( This. Savefiletype) { CaseText: This.            Textout.flush ();  This.            Textout.close ();  Break;  CaseBinary: This.            Binaryout.flush ();  This.            Binaryout.close ();  Break; default:             Break; }                return true; }  /*** Save the string as a text file (once) * *@paramdatastr * File contents *@paramSavepath * file path, including file name, suffix *@return     * @throwsIOException*/     Public Booleansavetextfile (String datastr, string savepath)throwsIOException {if(Datastr = = "" | | Datastr = =NULL) {System.out.println ("The DATASTR is null."); return false; }        if(Savepath = = "" | | Savepath = =NULL) {System.out.println ("The Savepath is null."); return false; } File datafile=NewFile (Savepath); if(!Datafile.getparentfile (). exists ())        {Datafile.getparentfile (). Mkdirs (); }        if(Datafile.exists ()) {datafile.delete ();        } datafile.createnewfile ();        BufferedWriter out; out=NewBufferedWriter (NewFileWriter (datafile));        Out.append (DATASTR);        Out.flush ();        Out.close (); return true; }    /*** Double-precision storage as binary data (stored once) * *@paramDatastr A string consisting of double-precision data separated by several spaces *@paramOutputPath *@return     * @throwsIOException*/     Public BooleanSavebinaryfile (String datastr, String OutputPath)throwsIOException {if(Datastr = = "" | | Datastr = =NULL) {System.out.println ("The DATASTR is null."); return false; }        if(OutputPath = = "" | | OutputPath = =NULL) {System.out.println ("The OutputPath is null."); return false; } File datafile=NewFile (OutputPath); if(!Datafile.getparentfile (). exists ())        {Datafile.getparentfile (). Mkdirs (); }        if(Datafile.exists ()) {datafile.delete ();        } datafile.createnewfile ();        DataOutputStream out; out=NewDataOutputStream (NewFileOutputStream (datafile)); //Data ProcessingDatastr=Datastr.trim (); String[] DataArray=datastr.split ("\\s+");  for(inti=0;i<dataarray.length;i++) {out.write (Double2bytes (double.parsedouble (dataarray[i)));        } out.flush ();        Out.close (); return true; }}

Code description: Where byte[] and double into the Internet to find the method, specifically which of the great God I forget, here for the record is posted, the above code contains the processing of small files, all content in the cache, and then write to the text file, binary file method, Also contains a read-write method for larger files, and here is a read-write test of your own.

/*** Test Binary Large file read/write (around 200M) *@authorCK **/ Public classFiletest {StaticString inputfilepath= "";//input file path, including filename suffix    StaticString outputfilepath= "";//output file name, including file name suffix         Public Static voidFile2file ()throwsioexception{datautil datautil=NewDatautil (); DataInputStream BR=NewDataInputStream (NewBufferedinputstream (NewFileInputStream (Inputfilepath)); Datautil.beginsave (Outputfilepath, Savefiletype.text); //Initialize, create files, use file Append storage idea byte[] Onedata=New byte[8]; intI=0,count =0 ;  while(Br.read (onedata, 0, 8)!=-1) {i=i+1;                                        Datautil.addsave (String.valueof (datautil.bytes2double (Onedata))); if(i/23543==0) {Count++; System.out.println (Count+ "\ n");       }} datautil.endsave ();     //Writes data that is also in the cache to a file, closing the file. }}

The test code quickly ran out, but the output file generated about half a minute (deliberately stopwatch time), try to use a one-time reading and writing method, the card is long, there is no results. The resulting decimal text file, the size of so many:

I think the original Fortran program author should be thinking that binary storage than the decimal space to save it, in fact, it does save more than half of the space.

Well, the record is complete.

Java ——— Reading and writing of large binary files

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.