需求:實際開發中讀取文本文件的需求還是很多,如讀取兩個系統之間FTP發送文件,讀取後保存到數據庫中或日志文件的數據庫中保存等。
為了測試首先利用數據庫SQL生成大數據文件。
規則是 編號|姓名|手機號,如 10|張10|13900000010
利用下面語句可以生成10,000,000條數據。
SELECT LEVEL||'|'||'張'||LEVEL||'|'||(13900000000+LEVEL) FROM DUAL CONNECT BYLEVEL < 1000000;
實現如下:
- package com.test.common.util;
- import Java.io.BufferedReader;
- import Java.io.File;
- import Java.io.FileInputStream;
- import Java.io.FileNotFoundException;
- import Java.io.FileReader;
- import Java.io.IOException;
- import Java.util.Scanner;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.io.LineIterator;
- public class HandleTextFile {
- // 使用commons-io.jar包的FileUtils的類進行讀取
- public static void readTxtFileByFileUtils(String fileName) {
- File file = new File(fileName);
- try {
- LineIterator lineIterator = FileUtils.lineIterator(file, "UTF-8");
- while (lineIterator.hasNext()) {
- String line = lineIterator.nextLine();
- System.out.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 使用Scanner進行讀取
- public static void readTxtByScanner(String fileName) {
- FileInputStream fileInputStream = null;
- Scanner scanner = null;
- try {
- fileInputStream = new FileInputStream(fileName);
- scanner = new Scanner(fileInputStream, "UTF-8");
- while (scanner.hasNext()) {
- String line = scanner.nextLine();
- System.out.println(line);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } finally {
- if (fileInputStream != null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (scanner != null) {
- scanner.close();
- }
- }
- }
- // 使用cache進行讀取
- public static void readTxtByStringBuffer(String fileName) throws IOException {
- File file = new File(fileName);
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new FileReader(file), 10 * 1024 * 1024);
- String stringMsg = null;
- while ((stringMsg = reader.readLine()) != null) {
- System.out.println(stringMsg);
- }
- reader.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- try {
- HandleTextFile.readTxtByStringBuffer("D:\\test\\customer_info.txt");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }