package Test;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class CSVFileWriterPrectice {
public static void main(String[] args) throws IOException {
Random random = new Random();
List<List<String>> csvList = new ArrayList<>();
String[] head = new String[] {"이름","나이","성별","주소"};
csvList.add(Arrays.asList(head));
for(int i=1; i<=100; i++) {
List<String> newLine = new ArrayList<>();
newLine.add(String.format("김은수%03d", i));
newLine.add(Integer.toString(random.nextInt(26)+20));
newLine.add(random.nextInt(2)==0) ? "남" : "여");
newLine.add(String.format("부산 해운대구%d", i));
csvList.add(newLine);
}
CSVWriter csvWriter = new CSVWriter(csvList);
csvWriter.writeCSV("myFirstCSV.csv");
}
}
class CSVWriter{
List<List<String>> csvList = new ArrayList<>();
public CSVWriter(List<List<String>> csvList) {
super();
this.csvList = csvList;
}
public void writeCSV(String strName) throws IOException {
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(strName),
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();
}
try {
if(bufferedWriter != null)
bufferedWriter.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
'코딩 > JAVA' 카테고리의 다른 글
GUI 이벤트 객체와 이벤트 소스 (0) | 2022.08.30 |
---|---|
GUI - JTebbedPane, ImageIcon 활용 예 (0) | 2022.08.30 |
StringTokenizer와 StringBuilder 사용 (0) | 2022.08.18 |
SimpleDataFormat 클래스 (0) | 2022.08.18 |
SimpleDataFormat 클래스 (0) | 2022.08.18 |