我正忙于使用 FileWriter,并且对编写文本文件的知识非常有限,我找到了一些我需要的示例,并用它们创建了自己的编码。我在 NetBeans 工作。
目标:
按下按钮时将 JTable 内容导出到文本文件。
问题:
bw.write(model.getValueAt(i, j));
错误前显示:找不到适合写入(输出)的方法...
这是怎么回事?
这个过程是这样的:
1)管理员运行首次运行配置
2) 管理员点击“添加用户”{1}
(Apps.Settings.FTRun)
3) 管理员通过输入字段来创建用户。单击“插入”,应用程序会创建一个用户 ID,然后将用户上传到数据库。此外,它将用户名和密码添加到 FTRun 中的表中。它应该添加元素,但事实并非如此! (代码如下)
Apps.UserManager.AddUser
4) 该表未填充,因此我在表中键入随机字符串。然后我点击 。这会引发 NullPointerException
这是我的代码:
1) 导出代码
2) 填充表代码
导出代码
try {
File file = new File("C:/Program Files/DocuLoc/bin/export.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
TableModel model = jTable1.getModel();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
//Create your File Writer
bw.write(model.getValueAt(i, j));
}
}
bw.close();
JOptionPane.showConfirmDialog(this, "Table exported successfully!\nFile located at " + file);
} catch (Exception e) {
e.printStackTrace();
}
填充表代码
try {
Apps.Settings.FTRun ftrun = new Apps.Settings.FTRun();
DefaultTableModel model = (DefaultTableModel) ftrun.jTable1.getModel();
model.addRow(new Object[]{UploadUName, UploadPwd});
ftrun.jTable1.enableInputMethods(true);
} catch (Exception e) {
e.printStackTrace();
}
最佳答案
我会使用:
bw.write( model.getValueAt(i, j).toString() );
它将写入您可能在 TableModel 中存储的任何对象的字符串表示形式。
编辑:
The NPE is caused by the bw.write(model.getValueAt(i,j).toString()); line
那么 null、“bw”、“model”、getValue(...) 方法中的数据是什么?
我猜测数据,因此您可以使用如下代码:
Object data = model.getValueAt(I, j);
if (data == null)
System.out.println("null data at - " + I + " : " + j);
else
bw.write( data.toString() );
一旦你知道哪些单元格为空,你就可以调查找出原因。
关于java - JTable FileWriter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866426/