CSV파일 처리
더보기
import java.io.BufferedReader;
import java.io.BufferedWriter;
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;
import java.util.List;
public class JavaExam {
public static void main(String[] args) {
CSVReader csvReader = new CSVReader();
List<List<String>> csvList = csvReader.readCSV();
csvReader.printCSV(csvList);
CSVWriter csvWriter = new CSVWriter(csvList);
csvWriter.writeCSV();
}
}
class CSVWriter{
List<List<String>> csvList;
public CSVWriter(List<List<String>> csvList) {
super();
this.csvList = csvList;
}
public void writeCSV() {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = Files.newBufferedWriter(
Paths.get("data1_write.csv"), Charset.forName("UTF-8"));
for(List<String> line : csvList) {
for(int i=0; i<line.size(); i++) {
bufferedWriter.write(line.get(i));
if(i != line.size()-1)
bufferedWriter.write(",");
}
bufferedWriter.newLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(bufferedWriter != null)
bufferedWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CSVReader{
List<List<String>> csvList;
public CSVReader() {
this.csvList = readCSV();
}
public void printCSV(List<List<String>> csvList) {
for(int i=0; i<csvList.size();i++) {
for(int j=0; j<csvList.get(i).size();j++) {
System.out.print(csvList.get(i).get(j)+" ");
}
System.out.println();
}
}
public List<List<String>> readCSV(){
List<List<String>> csvList = new ArrayList<List<String>>();
BufferedReader bufferedReader = null;
try {
bufferedReader = Files.newBufferedReader(Paths.get("data1.csv")
,Charset.forName("UTF-8")); //"MS949", "UTF-8", "EUC-KR"
String line = "";
while((line=bufferedReader.readLine()) != null) {
List<String> aLine = new ArrayList<String>();
String[] lineArr = line
.replace("\"", "")
.replace("\uFEFF", "").split(",");
aLine = Arrays.asList(lineArr);
csvList.add(aLine);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally {
try {
if(bufferedReader != null)
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return csvList;
}
}
'PROGRAM > JAVA' 카테고리의 다른 글
GUI #2 (0) | 2022.08.30 |
---|---|
GUI (0) | 2022.08.29 |
Intellij 시작하기 (0) | 2020.11.09 |
JDK 1.8.0_271 설치하기 (0) | 2020.10.21 |
Thread TimerEx (0) | 2020.06.20 |