你能幫我這個,我想添加2來自CSV的整數,並將其存儲在txtfile,但問題是這是字符串,如果我把它轉換爲一個整數我有很多錯誤。 。謝謝你們..如何將CSV字符串轉換爲整數並添加它。存儲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
應該BR:
che,cheche,chet
100,100,100
100,100,100
che - 200
cheche -200
chet - 200
如果您告訴我們哪些錯誤,這將有所幫助。 – 2013-03-14 10:35:49
如何將字符串轉換爲整數? – PermGenError 2013-03-14 10:36:04
Try student.setScore1(Integer.parseInt(dataArray [1])); – Jayamohan 2013-03-14 10:51:15