我应该创建一个程序,以电子表格格式显示可编辑的CSV,然后从LDAP源中提取信息并将其附加到所述电子表格中并保存。因为蝙蝠的处理很多,我一次只能把它拿出来。
甚至没有打扰LDAP位,我只想获得Load>编辑>保存位现在可以工作。
我认为如果我开始使用打开,显示和保存.TXT文件,我可以轻松地将我学到的东西转移到以后实现.CSV部分时。但是,我很难让保存部分正常工作(完全阅读),我在这里阅读其他帖子时得到了一些帮助,所以我想我会问。
注意:JFileChooser的Oracle Java tute不包括保存,除了几乎没有涉及如何开始实现它,而不是它实际上如何运行。
指向我的代码的链接: http://pastebin.com/tWnYrwgM
目前我需要最多帮助的代码:
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
//TODO
}
我目前没有任何东西,因为当我在那里编写代码时,当我构建,运行或调试项目时,我从未真正得到任何工作。
我想我想说的是我在写文件时遇到了麻烦。
答案 0 :(得分:0)
好的,这将是您需要做的示例实现。 请注意,虽然这适用于基本情况,但还不够。使用已建立的CSV库可以做得更好,这仅用于教育目的。
JTable myTable;
public void actionPerformed(ActionEvent e) {
try {
TableModel model = myTable.getModel(); // the table model contains all the data. Read its JavaDoc API it is enlightend when you work with JTables and you can do lots of neat stuff with it.
JFileChooser fc = new JFileChooser();
if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { // no save when the user canceled.
File target = fc.getSelectedFile();
FileWriter fWri = new FileWriter(target); // this will create the file, but not any parent directories that might not exist. If there are parent directories that don't exist, this line will throw a FileNotFoundException.
for(int ii = 0; ii < model.getRowCount(); ii++) {
StringBuilder lineValue = new StringBuilder();
for(int jj = 0; ii < model.getColumnCount(); jj++) {
lineValue.append(model.getValueAt(ii, jj));
lineValue.append(",");
}
lineValue.substring(0, lineValue.length() -1); // cut away the last ,
fWri.write(lineValue + "\r\n"); // the RFC suggests CRLF, but don't be surprised when you get a CSV from somewhere that has only LF or something. Its because of lines like this that you want a library handle it for you.
}
fWri.flush();// in fact, this and the next line should go to a 'finally' block. Read about correct and clean file writing to learn more.
fWri.close();
}
} catch (IOException ioex) {
// file not found, cant be written to, etc. You handle it here.
}
}