Java reads files-extracts files by row (using BufferedReader and saving data to memory at one time), javabufferedreader

Source: Internet
Author: User

Java reads files-extracts files by row (using BufferedReader and saving data to memory at one time), javabufferedreader

1. Goals

Read the file and extract one row of data from the file.

2. Code Implementation

1) Method 1:

Use the readLine () method of BufferedReader.

/*** Function: Java reads the txt file content step: 1: Get the file handle first 2: Get the file handle as input a byte code stream, you need to read this input stream * 3: after reading the input stream, you need to read the generated byte stream 4: output of one row. Readline (). Note: you need to consider the exception ** @ param filePath * file path [reaching the file: for example, D: \ aa.txt] * @ return splits the file into arrays and stores them in the list. */Public static List <String> readtxtfile1_stringarrlist (String filePath) {List <String> list = new ArrayList <String> (); try {String encoding = "GBK "; file file = new File (filePath); if (file. isFile () & file. exists () {// determine whether the file exists InputStreamReader read = new InputStreamReader (new FileInputStream (file), encoding); // take into account the encoding format BufferedReader bufferedReader = new BufferedReader (read ); string lin ETxt = null; while (lineTxt = bufferedReader. readLine ())! = Null) {list. add (lineTxt);} bufferedReader. close (); read. close ();} else {System. out. println ("the specified file cannot be found");} catch (Exception e) {System. out. println ("An error occurred while reading the file content"); e. printStackTrace ();} return list ;}

2) method 2

Save the content in the file through the byte array of the file, convert it to String data, and then split it according to "carriage return.

/*** Read the filePath file, read the data in the file to the * @ param filePath file path * @ return file in the String array */public static String [] readToString (String filePath) {File file = new File (filePath); Long filelength = file. length (); // get the object length byte [] filecontent = new byte [filelength. intValue ()]; try {FileInputStream in = new FileInputStream (file); in. read (filecontent); in. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} String [] fileContentArr = new String (filecontent ). split ("\ r \ n"); return fileContentArr; // returns the file content, default encoding}

3) test

Public static void main (String [] args) {List <String> stringList = readtxtfile1_stringarrlist ("C: \ soft \ java \ tomcat \ apache-tomcat-7.0.40 \ webapps \ appDataGenerate \ log4j \ lepai_recognize_cache.log "); System. out. println ("------- use BufferedReader to read -----------"); for (String str: stringList) {System. out. println (str);} System. out. println ("\ n --------- use byte to directly cache the entire file to the memory ----------------"); String [] stringArr = readToString ("C: \ soft \ java \ tomcat \ apache-tomcat-7.0.40 \ webapps \ appDataGenerate \ log4j \ lepai_recognize_cache.log "); for (int I = 0; I <stringArr. length; I ++) {System. out. println (stringArr [I]) ;}}

Result:

------- Use BufferedReader to read ----------- [13:21:28] [RecognizeCache] [INFO]: RecogizeCache init [13:21:28] [RecognizeCache] [INFO]: recogizeCache init [13:21:28] [RecognizeCache] [INFO]: RecogizeCache init [13:21:28] [updated] [INFO]: RecogizeCache init [14:52:04] [RecognizeCache] [INFO]: read File: bytes --------- use byte to directly cache the entire file to the memory -------------- [13:21:28] [RecognizeCache] [INFO]: RecogizeCache init [13:21:28] [RecognizeCache] [INFO]: recogizeCache init [13:21:28] [RecognizeCache] [INFO]: RecogizeCache init [13:21:28] [updated] [INFO]: RecogizeCache init [14:52:04] [RecognizeCache] [INFO]: read the file: 4209bad42de0f6e55c0daf0bd24b635a.txt

3. Comparison

Method 1:Part or allData is read out and cached using BufferReader. data needs to be read from the cache, which is faster than reading from the file.

Method 2 is to read the original content of the text directly to the memory for processing (the memory size is not considered for the time being), which will improve the efficiency. At the same time, it can be used to process when you use the readLine () method in the 1st method, and the file has threads constantly writing data to the file [only processing data already in the file ]. In addition, using methods such as readline () may require repeated file access, and each time readline () calls encoding conversion, which reduces the speed. Therefore, when the encoding is known, the fastest way is to read all files into the memory in byte stream mode, and then perform one-time Encoding and conversion.

If you have any mistakes, please kindly advise me. For more information,

1. How can I determine whether the other party's files have been written by using ftp to fetch a file locally.

2. When I use the readLine () method of BufferedReader to read a file in one row, I also add data to the file. Will the reading of the file fail.

Download source code:

TestReadAllFileToMemory for the https://github.com/zcr1007391008/demo.

Thank you!

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.