Java reads all the contents of a text file at once

Source: Internet
Author: User

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

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.