简体   繁体   English

将JTable导出到txt文件

[英]Exporting JTable to txt file

Interesting little error here, hopefully someone can point out what's happening to me. 这里有趣的小错误,希望有人能指出我发生了什么。

My program is able to write to a text file if there's approximately 4 or less entries in the JTable. 如果JTable中大约有4个或更少的条目,我的程序就可以写入文本文件。 Once there's more than that it fails and throws an exception that pops up my catch block. 一旦超过了该数量,它就会失败并引发异常,并弹出我的catch块。 Not sure what's happening. 不知道发生了什么。

public void actionPerformed(ActionEvent e)
    {
        try
        {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("payrollData.txt"));
            PrintWriter fileWriter = new PrintWriter(bufferedWriter);

            for(int i = 0; i < outputTable.getRowCount()+1; i++)
            {     
                String headers = String.valueOf(outputTable.getColumnName(i));
                fileWriter.print(headers);
                fileWriter.print("\t");
            }   

            fileWriter.println("");
            for(int i=0; i<model.getRowCount(); ++i)
            {
                for(int j=0; j<model.getColumnCount(); ++j)
                {
                    String s = model.getValueAt(i,j).toString();
                    fileWriter.print(s);
                    fileWriter.print("\t\t");
                }
                fileWriter.println("");
            }      
            fileWriter.close();
            JOptionPane.showMessageDialog(null, "Success. File saved to payrollData.txt");
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Failure");
        }

edit: added ex.printStackTrace(); 编辑:添加了ex.printStackTrace(); and it shows an array index out of bounds exception 它显示了数组索引超出范围的异常

So, having a look at this... 所以,看看这个...

for(int i = 0; i < outputTable.getRowCount()+1; i++)
{     
    String headers = String.valueOf(outputTable.getColumnName(i));
    fileWriter.print(headers);
    fileWriter.print("\t");
} 

I'm left wondering what getRowCount has to do with the number of columns ... pherhaps you meant getColumnCount ... which would means you could also get rid of the +1 我只是想知道getRowCount与列数有什么关系……您可能是说getColumnCount ...这意味着您也可以摆脱+1

Observations... 观察...

Having spent some time running over the code, there are a couple of other minor observations I can make. 花了一些时间运行代码之后,我还可以进行一些其他的观察。

First, I'd highly encourage the use of The try-with-resources Statement , this will allow you to better manage your resources. 首先,我强烈建议您使用try-with-resources语句 ,这将使您更好地管理资源。

I'd also suggest using StringJoiner to generate each line, it's simpler then trying to check if you're writing out the last column or not and allows you supply what ever delimiter you want to use 我还建议使用StringJoiner生成每一行,然后尝试检查是否要写出最后一列更简单,并允许您提供要使用的分隔符

As an example... 举个例子...

DefaultTableModel model = new DefaultTableModel();
model.addColumn("Purpose");
model.addColumn("Name");
model.addColumn("Composition");
model.addColumn("Expiry");
model.addColumn("Stock");
model.addColumn("Cost");
model.addColumn("Type");
model.addColumn("Supplier");
model.addColumn("Supplier Number");
model.addColumn("Rack");

for (int index = 0; index < 10; index++) {

    Vector vector = new Vector();
    vector.add("p" + index);
    vector.add("n" + index);
    vector.add("c" + index);
    vector.add("e" + index);
    vector.add("s" + index);
    vector.add("c" + index);
    vector.add("t" + index);
    vector.add("s" + index);
    vector.add("s" + index);
    vector.add("r" + index);

    model.addRow(vector);

}

JTable table = new JTable(model);

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Test.txt")))) {
    StringJoiner joiner = new StringJoiner(",");
    for (int col = 0; col < table.getColumnCount(); col++) {
        joiner.add(table.getColumnName(col));
    }
    System.out.println(joiner.toString());
    bw.write(joiner.toString());
    bw.newLine();
    for (int row = 0; row < table.getRowCount(); row++) {
        joiner = new StringJoiner(",");
        for (int col = 0; col < table.getColumnCount(); col++) {
            Object obj = table.getValueAt(row, col);
            String value = obj == null ? "null" : obj.toString();
            joiner.add(value);
        }
        System.out.println(joiner.toString());
        bw.write(joiner.toString());
        bw.newLine();
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM