你能帮我解决这个问题吗,我想添加来自 CSV 的 2 个整数并将其存储在 txtfile 中,但问题是它是字符串,如果我将其转换为整数,我会遇到很多错误。谢谢你们。 .
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main (String[]arg)throws Exception {
String readFile = "C:/Users/user/Desktop/student.csv";
String writeFile = "C:/Users/user/Desktop/data.txt";
// Read a comma-separated values (CSV) file.
BufferedReader CSVFile = new BufferedReader (new FileReader(readFile));
// Read line.
String dataRow = CSVFile.readLine();
// Create an array of student
List<Student> students = new ArrayList <Student> ();
// The while checks to see if the data is null. If
// it is, we’ve hit the end of the file. If not,
// process the data.
while (dataRow !=null){
String [] dataArray = dataRow.split(",");
System.out.println(dataRow);
Student student = new Student();
student.setStudentName(dataArray[0]);
student.setScore1(dataArray[1]);
student.setScore2(dataArray[2]);
students.add(student);
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(writeFile);
for (Student s : students){
sb.append(s.studentName);
System.out.println(s.studentName + " - " + (s.score1 + s.score2));
// Writing to a text file.
fw.write(sb.toString());
}
// Close the file once all data has been written.
fw.close();
}
}
输出:
che,cheche,chet
100,100,100
100,100,100
null - 0
null - 0
null - 0
它应该是:
che,cheche,chet
100,100,100
100,100,100
che - 200
cheche -200
chet - 200