这是我用于csv编辑器的代码?它读取csv文件并在自定义表中显示并允许编辑,但我无法保存并更新它。
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class T1Data {
public static void main(String[] args) {
try {
String path = System.getProperty("user.dir");
String csvName = "effects";
String datafile = path+"/files/logic/"+csvName+".csv";
FileReader fin = new FileReader(datafile);
DefaultTableModel m = createTableModel(fin, null);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(m);
JScrollPane stable = new JScrollPane (table);
stable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
stable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
f.getContentPane().add(stable);
f.setSize(1000, 600);
f.setVisible(true);
toExcel(m, new File(path+"/files/logic/"+csvName+".csv"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void toExcel(TableModel model, File file){
try{
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + ",");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+",");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static DefaultTableModel createTableModel(Reader in, Vector<Object> headers) {
DefaultTableModel model = null;
Scanner s = null;
try {
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
s = new Scanner(in);
while (s.hasNextLine()) {
rows.add(new Vector<Object>(Arrays.asList(s.nextLine().replace('"',' ') .split("\\s*,\\s*",-1))));
}
if (headers == null) {
headers = rows.remove(0);
model = new DefaultTableModel(rows, headers);
} else {
model = new DefaultTableModel(rows, headers);
}
return model;
} finally {
s.close();
}
}
}
它将打开effects.csv文件并显示如下: http://gyazo.com/fef8397deb3bcaa6dd93d03715f8262a.png
然后它允许我编辑值但不保存它。我希望当我关闭窗户时它会保存,但我无法让它工作。我还将添加一个按钮以便稍后保存。
如何让保存和更新正常工作?