기존 CSV 파일에 데이터 추가
이제 CSV 파일을 만들었으므로, Java 프로그램을 수정하여 기존 파일을 덮어쓰는 대신 추가 데이터를 기존 파일에 추가해 보겠습니다.
CSVAppendExample.java라는 새 Java 파일을 생성합니다.
touch src/main/java/com/example/CSVAppendExample.java
- WebIDE 편집기에서
CSVAppendExample.java를 열고 다음 코드를 추가합니다.
package com.example;
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.IOException;
public class CSVAppendExample {
public static void main(String[] args) {
try {
// Create a CSVWriter in append mode by setting the second parameter of FileWriter to true
CSVWriter writer = new CSVWriter(new FileWriter("students.csv", true));
// Write additional data to the existing file
String[] student3 = {"Robert Johnson", "24", "robert.johnson@example.com"};
writer.writeNext(student3);
String[] student4 = {"Maria Garcia", "23", "maria.garcia@example.com"};
writer.writeNext(student4);
// Close the writer
writer.close();
System.out.println("Data appended to CSV file successfully!");
} catch (IOException e) {
System.out.println("Error appending to CSV file: " + e.getMessage());
e.printStackTrace();
}
}
}
이 코드는 이전 예제와 유사하지만 두 가지 중요한 차이점이 있습니다.
FileWriter를 두 번째 매개변수를 true로 설정하여 추가 모드로 생성합니다.
- 파일에 이미 헤더 행이 있으므로 헤더 행을 쓰지 않습니다.
- 프로그램을 실행하여 기존 CSV 파일에 데이터를 추가합니다.
cd ~/project/csv-writer
mvn exec:java -Dexec.mainClass="com.example.CSVAppendExample"
- 이제 CSV 파일의 내용을 확인해 보겠습니다.
cat students.csv
원래 데이터와 새로 추가된 레코드를 볼 수 있습니다.
"Name","Age","Email"
"John Doe","25","john.doe@example.com"
"Jane Smith","22","jane.smith@example.com"
"Robert Johnson","24","robert.johnson@example.com"
"Maria Garcia","23","maria.garcia@example.com"
보시다시피 새 데이터는 기존 내용을 방해하지 않고 파일 끝에 추가되었습니다.
- 사용자 지정 구분 기호로 CSV 파일을 쓰는 방법을 보여주는 예제를 하나 더 만들어 보겠습니다.
touch src/main/java/com/example/CSVCustomExample.java
- WebIDE 편집기에서
CSVCustomExample.java를 열고 다음 코드를 추가합니다.
package com.example;
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.IOException;
public class CSVCustomExample {
public static void main(String[] args) {
try {
// Create a CSVWriter with semicolon as separator instead of comma
CSVWriter writer = new CSVWriter(new FileWriter("students_semicolon.csv"),
';',
CSVWriter.DEFAULT_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
// Write header line
String[] header = {"Name", "Age", "Email"};
writer.writeNext(header);
// Write data lines
String[] student1 = {"John Doe", "25", "john.doe@example.com"};
writer.writeNext(student1);
String[] student2 = {"Jane Smith", "22", "jane.smith@example.com"};
writer.writeNext(student2);
// Close the writer
writer.close();
System.out.println("CSV file with semicolon separator created successfully!");
} catch (IOException e) {
System.out.println("Error writing to CSV file: " + e.getMessage());
e.printStackTrace();
}
}
}
이 예제는 쉼표 대신 세미콜론을 구분 기호로 사용하여 CSV 파일을 생성합니다. 이는 쉼표를 소수점 구분 기호로 사용하는 일부 유럽 국가에서 흔히 사용됩니다.
- 사용자 지정 구분 기호 예제를 실행합니다.
cd ~/project/csv-writer
mvn exec:java -Dexec.mainClass="com.example.CSVCustomExample"
- 새 CSV 파일의 내용을 확인합니다.
cat students_semicolon.csv
세미콜론을 구분 기호로 사용하는 CSV 파일을 볼 수 있습니다.
"Name";"Age";"Email"
"John Doe";"25";"john.doe@example.com"
"Jane Smith";"22";"jane.smith@example.com"