新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java讀取大文件方法
需求:實際開發(fā)中讀取文本文件的需求還是很多,如讀取兩個系統(tǒng)之間FTP發(fā)送文件,讀取后保存到數(shù)據(jù)庫中或日志文件的數(shù)據(jù)庫中保存等。

目前成都創(chuàng)新互聯(lián)已為上千多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站托管、服務(wù)器托管、企業(yè)網(wǎng)站設(shè)計、武定網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
為了測試首先利用數(shù)據(jù)庫SQL生成大數(shù)據(jù)文件。
規(guī)則是 編號|姓名|手機號,如 10|張10|13900000010
利用下面語句可以生成10,000,000條數(shù)據(jù)。
SELECT LEVEL||'|'||'張'||LEVEL||'|'||(13900000000+LEVEL) FROM DUAL CONNECT BY LEVEL < 1000000;
實現(xiàn)如下:
- 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();
- }
- }
- }
參考文件:讀取大文件性能測試
當(dāng)前標(biāo)題:Java讀取大文件方法
瀏覽路徑:http://m.fisionsoft.com.cn/article/djjjsio.html


咨詢
建站咨詢
