问题
I writing JTable
data into CSV file using OpenCSV jar. Everything works fine unless it comes to read data from the table data. Whenever I am choosing the first row it works perfectly. But when I am choosing the more than one row it gives the exception which is mentioned in the title.
Below is the code:
DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel();
int rows = Integer.parseInt((String)jTextField8.getText());
String fileName = jTextField11.getText()+".csv";
File file = new File("/Users/startelelogic/Desktop/fileName");
if (jTable1.isEditing()){
jTable1.getCellEditor().stopCellEditing();
}
try{
FileWriter outputFile = new FileWriter(fileName);
CSVWriter writer = new CSVWriter(outputFile);
// Adding Header to csv File
String header[] = {"Sr. No.","CM","Liters"};
writer.writeNext(header);
// Adding data to csv
System.out.println("Rows \t:"+rows);
for(int i=0; i<rows; i++){
String[] data = new String[3];
for(int j=0; j< tableModel.getColumnCount(); j++){
data[j] = (String)tableModel.getValueAt(i, j);
}
writer.writeNext(data);
writer.close();
}
JOptionPane.showMessageDialog(null, "Table Data Written successfully!");
}catch(IOException ex){
JOptionPane.showMessageDialog(null, "FileWriting error");
ex.printStackTrace();
}
回答1:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
Well the error message is telling you the problem. You can't make an Integer object be a String object.
data[j] = (String)tableModel.getValueAt(i, j);
The above statement assumes all data in the table is an instance of String.
Instead you can use:
data[j] = tableModel.getValueAt(i, j).toString();
Now you data array will contain the String representation of every object.
来源:https://stackoverflow.com/questions/61403516/exception-in-thread-awt-eventqueue-0-java-lang-classcastexception-class-java