We do the text processing of the most commonly used is to read and write files, especially read files, no matter what file, I tend to the original content of the text directly read into memory and then do processing, of course, this requires you have a large memory of the machine, not enough memory of the person ... You can read a small portion of content at a time and read multiple times.
The fastest way to read a file is to read it all at once, a lot of people using readline () and other methods, may need to repeatedly access the file, and each time ReadLine () will call the encoding conversion, reduce the speed, so, in the case of known encoding, by byte stream read the file into memory, Again the one-time encoding conversion is the quickest way, the typical code is as follows:
Publicstring readtostring (String fileName) {string encoding= "UTF-8"; File File=NewFile (fileName); Long Filelength=file.length (); byte[] Filecontent =New byte[Filelength.intvalue ()]; Try{FileInputStream in=Newfileinputstream (file); In.read (filecontent); In.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Try { return NewString (filecontent, encoding); } Catch(unsupportedencodingexception e) {System.err.println ("The OS does not support" +encoding); E.printstacktrace (); return NULL; } }
Java reads all the contents of a text file at once