웹 개발/Java
[Java] CSV 파일 읽기
개발 기록
2024. 12. 26. 14:45
엑셀(.xlsx) 읽는 방법이랑 csv파일 읽는 방법이 달라서 기록
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
improt java.util.List;
public class Main{
public static void main(string[] arg){
// 반환 데이터 담을 리스트
List<List<String>> ret = new ArrayList<List<String>>();
// 입력 스트림 생성
BufferedReader br = null;
try{
// 대상 CSV 파일의 경로
br = Files.newBufferedReader(Path.get("C:\\Desktop\\Test.csv"),Charset.forName("UTF-8"));
// 읽은 1행분의 데이터
String line = "";
while((line = br.readLine()) != null){
// csv 파일의 1행분의 데이터를 저장할 리스트
List<String> dataList = new ArrayList<List<String>>();
String array[] = line.split(",");
// 배열 => 리스트
dataList = Arrays.asList(array);
// 데이터 저장
ret.add(dataList);
} // while
} catch(Exception e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}