Java로 텍스트 파일 읽기

버퍼 방식으로 사용하여 빠르게 텍스트 파일을 읽는 예제 코드입니다. 제가 Java 아재라서, 새로운 Java의 더욱 효과적인 파일 읽기 API가 분명 있을것 같은데.. 혹 있다면 추천 부탁드리겠습니다.

package tst;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class MainEntry {
	public static void main(String[] args) {
		String filePath = "D:\\__Data__\\DXF\\1_5000\\NGII_DTM_5000_울산_남구_35905\\35905090.dxf";

		FileInputStream fs = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		
		try {
			long startTime = System.currentTimeMillis();
			
			fs = new FileInputStream(filePath);
			isr = new InputStreamReader(fs, "euc-kr");
			br = new BufferedReader(isr);
			
			String line = null;
			while((line = br.readLine()) != null) {
				//System.out.println(line);
			}
			
			long finishTime = System.currentTimeMillis();
			System.out.println("소요시간: " + (finishTime - startTime) + " ms");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(br != null) br.close();
				if(isr != null) isr.close();
				if(fs != null) fs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

위의 코드로 7.52MB 크기의 파일을 모두 읽는데, 약 0.13초정도 소요됩니다. 사용하고 있는 개발 환경은 i7-6700HQ@2.60GHz의 RAM 16GB 노트북입니다.

Python에서 외부 데이터 파일 읽기

파이썬에서 다양한 데이터 파일을 읽어오는 코드를 정리한 글로 추후 빠르게 참조하기 위한 목적으로 작성 되었습니다.

CSV 파일 읽기

import csv

rows = []
with open('../data/fileName.csv') as csvfile:
    csvreader = csv.reader(csvfile)
    next(csvreader, None)
    for row in csvreader:
        rows.append(row)

3번의 next 함수는 csv 파일의 첫줄에 있는 필드명을 건너뛰기 위함입니다. rows에 데이터가 저장됩니다.

JSON 파일 읽기

import json

with open('../data/fileName.json') as jsonfile:
    data = json.load(jsonfile)
    value_plainType = data["key1"]
    value_arrayType = data["key2"]
    value_dictionaryType = data["key3"]

    print(value_plainType)
    print(value_arrayType)
    print(value_dictionaryType["name"])

위의 fileName.json 파일의 내용이 다음과 같을때..

{
    "key1" : "string/numeric/bool",
    "key2" : [1, 2, 3, 4, 5],
    "key3" : { "name":"DoWise", "age": 12 }
}

출력 결과는 다음과 같습니다.

string/numeric/bool
[1, 2, 3, 4, 5]
DoWise