JAVA
File I/O - loading data and creating txt file from CSV file.
seoca
2019. 7. 5. 05:16
students.csv
id,name
1,A
2,B
3,C
public class StudentInfo { private int id; private String name; public StudentInfo(int id, String name){ this.id = id; this.name = name; } public int studentId(){ return id; } @Override public String toString(){ return "Student Id: " + this.id + ", " + "name: " + this.name + "\n"; } }
public class Main {
public static void main(String[] args) throws FileNotFoundException {
//ArrayList
ArrayList<StudentInfo> studentInfos = new ArrayList<>();
try {
//read the CSV file
BufferedReader sc = new BufferedReader(new FileReader("src" + File.separator + "csv_input" + File.separator + "students.csv"));
//skip the first line
String re = sc.readLine(); //id, name
//while loop until the end of file
while ((re = sc.readLine()) != null) {
//while (re != null) { // If only 're' assigned, NumberFormatException error will occur because 're' has 'id','name' as String
//split comma-separated
String[] data = re.split(",");
//way1. create method
//assign to ArrayList
//StudentInfo student = createFile(data);
//studentInfos.add(student);
//way2. creating object inside the add method.
studentInfos.add(new StudentInfo(Integer.parseInt(data[0]), data[1]));
//re = sc.readLine(); // If the data is String, assigning 're' and put this line to read next line is fine.
//But, It occurs Error here. Because, this example have to convert String to Int to calculate.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//create text file
File file = new File("src" + File.separator + "txt_output" + File.separator + "reportCard.txt");
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getPath()), StandardCharsets.UTF_8));
try {
for (int i = 0; i < studentInfos.size(); i++) {
output.write(studentInfos.get(i).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// way1. declare createFile method to assign data
// private static StudentInfo createFile(String[] s) {
// int id = Integer.parseInt(s[0]);
// String name = s[1];
// return new StudentInfo(id, name);
// }
}
|
reportCard.txt
Student Id: 1, name: A
Student Id: 2, name: B
Student Id: 3, name: C