Read and write files in Java, reading large files

Source: Internet
Author: User

has been in the processing of reptiles, often can encounter read and write files, many times are read and write oversized files, recorded as follows: First, read the fileImportJava.io.BufferedOutputStream; ImportJava.io.BufferedReader; ImportJava.io.File; ImportJava.io.FileOutputStream; ImportJava.io.FileReader; ImportJava.io.FileWriter; Importjava.io.IOException; ImportJava.io.OutputStreamWriter;  Public voidReadFile (String filename) {file file=NewFile (filename); BufferedReader Reader=NULL; Try{Reader=NewBufferedReader (NewFileReader (file));//If you are reading large files then new BufferedReader (new FileReader (file), 5*1024*1024); That is, set the cacheString tempstring=NULL;  while((Tempstring=reader.readline ())! =NULL)               {                    //to operate .....} reader.close (); }Catch(IOException e) {e.printstacktrace (); }finally{           if(reader!=NULL)         {               Try{reader.close (); }Catch(IOException e) {e.printstacktrace (); }}} II, write fileImportJava.io.BufferedOutputStream; ImportJava.io.BufferedReader; ImportJava.io.BufferedWriter; ImportJava.io.File; ImportJava.io.FileOutputStream; ImportJava.io.FileReader; ImportJava.io.FileWriter; Importjava.io.IOException; ImportJava.io.OutputStreamWriter;  Public voidmethod1 (String file,string content) {BufferedWriter out=NULL; Try{ out=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (file,true)));//Additional Methodsout.write (content); Out.write ("\ r \ n"); }Catch(IOException e) {e.printstacktrace (); }finally{     Try{out.close (); }Catch(IOException e) {e.printstacktrace (); }}} Public voidMain (string[] args) {String filename= "D:\a.txt"; File F=NewFile (filename);if(F.exists ()) {F.delete ();} F.createnewfile (); String SS= "Sssssss"; method1 (FILENAME,SS);}=========================== Ornate delimiter =============================in practice, it is possible to edit this article by discovering that the above method can handle data within 10M. To really deal with hundreds of meters, or even the file of G, it is necessary to use the Java NIO package: The following code goes from "http://www.oschina.net/code/snippet_54100_7938 "ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classTestnio { Public Static voidMain (String args[])throwsexception{intbufSize = 100; File Fin=NewFile ("D:\\workspace\\test\\usagetracking.log"); File Fout=NewFile ("D:\\workspace\\test\\usagetracking2.log"); FileChannel fcin=NewRandomaccessfile (FIN, "R"). Getchannel (); Bytebuffer Rbuffer=bytebuffer.allocate (bufSize); FileChannel fcout=NewRandomaccessfile (Fout, "RWS"). Getchannel (); Bytebuffer Wbuffer=Bytebuffer.allocatedirect (bufSize); Readfilebyline (BufSize, Fcin, Rbuffer, Fcout, Wbuffer); System.out.print ("OK!!!"); } /*read files and write files at the same time*/ Public Static voidReadfilebyline (intbufSize, FileChannel fcin, Bytebuffer rbuffer, FileChannel fcout, Bytebuffer wbuffer) {String Enterstr= "\ n"; Try{ byte[] bs =New byte[bufSize];intSize = 0; StringBuffer Strbuf=NewStringBuffer (""); //While (size = fcin.read (buffer))! =-1) { while(Fcin.read (rbuffer)! =-1){      intRsize =rbuffer.position ();      Rbuffer.rewind ();      Rbuffer.get (BS);      Rbuffer.clear (); String tempstring=NewString (BS, 0, rsize); //System.out.print (tempstring); //System.out.print ("<200>");     intFromIndex = 0; intEndIndex = 0;  while((EndIndex = Tempstring.indexof (Enterstr, fromIndex))! =-1) {String line=tempstring.substring (FromIndex, EndIndex); Line=NewString (strbuf.tostring () +Line ); //System.out.print (line); //System.out.print ("</over/>"); //write to Anthone filewritefilebyline (fcout, Wbuffer, line); Strbuf.delete (0, Strbuf.length ()); FromIndex= EndIndex + 1; }      if(Rsize >tempstring.length ())      {Strbuf.append (tempstring.substring (FromIndex, Tempstring.length ())); }Else{strbuf.append (tempstring.substring (FromIndex, rsize)); } } } Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} } /*Write a file*/ Public Static voidWritefilebyline (FileChannel fcout, Bytebuffer Wbuffer, String line) {Try { //write on File head//Fcout.write (Wbuffer.wrap (Line.getbytes ()));//wirte append file on footFcout.write (Wbuffer.wrap (Line.getbytes ()), fcout.size ()); Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} } } 

Read and write files in Java, reading large files

Related Article

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.