Java 从特定的 CSV 文件中读取数据并将其显示在 JTable 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22864095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:29:36  来源:igfitidea点击:

Reading data from a specific CSV file and displaying it in a JTable

javaswingcsvfile-iojtable

提问by user3460225

About this question: Reading data from CSV file and displaying it in a JTable

关于这个问题: 从 CSV 文件中读取数据并将其显示在 JTable 中

I tried to adapt the program of this question to make it fit to my need but it is making mistakes. I want the program to display a file located in the root of my project (so I have to write File DataFile = new File("res.csv");) that's all. The problem is that it displays only 2 lines, when 4 lines are supposed to be displayed.

我试图调整这个问题的程序以使其适合我的需要,但它正在犯错误。我希望程序显示位于我的项目根目录中的文件(所以我必须编写File DataFile = new File("res.csv");),仅此而已。问题是它只显示 2 行,而应该显示 4 行。

Here is the code :

这是代码:

import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
import javax.swing.table.*;

public class T1Data extends JPanel {
    private final JTable table;

    public T1Data() {
        super(new BorderLayout(3, 3));

        this.table = new JTable(new MyModel());
        this.table.setPreferredScrollableViewportSize(new Dimension(700, 70));
        this.table.setFillsViewportHeight(true);

        JPanel ButtonOpen = new JPanel(new FlowLayout(FlowLayout.CENTER));
        add(ButtonOpen, BorderLayout.SOUTH);

        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        // Add the scroll pane to this panel.
        add(scrollPane, BorderLayout.CENTER);

        // add a nice border
        setBorder(new EmptyBorder(5, 5, 5, 5));

        CSVFile Rd = new CSVFile();
        MyModel NewModel = new MyModel();
        this.table.setModel(NewModel);
        File DataFile = new File("res.csv");
        ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);

        NewModel.AddCSVData(Rs2);
        System.out.println("Rows: " + NewModel.getRowCount());
        System.out.println("Cols: " + NewModel.getColumnCount());

    }

    // Method for reading CSV file
    public class CSVFile {
        private ArrayList<String[]> Rs = new ArrayList<>();
        private String[] OneRow;

        public ArrayList<String[]> ReadCSVfile(File DataFile) {
            try {
                BufferedReader brd = new BufferedReader(
                        new FileReader(DataFile));

                while (brd.readLine() != null) {
                    String st = brd.readLine();
                    OneRow = st.split(",|\s|;");
                    Rs.add(OneRow);
                    System.out.println(Arrays.toString(OneRow));
                } // end of while
            } // end of try
            catch (Exception e) {
                String errmsg = e.getMessage();
                System.out.println("File not found:" + errmsg);
            } // end of Catch
            return Rs;
        }// end of ReadFile method
    }// end of CSVFile class

    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("T1Data");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create and set up the content pane.
        T1Data newContentPane = new T1Data();
        frame.setContentPane(newContentPane);

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    class MyModel extends AbstractTableModel {
        private String[] columnNames = { "1", "2", "3", "4", "5", "6", "7", "8" };
        private ArrayList<String[]> Data = new ArrayList<>();

        public void AddCSVData(ArrayList<String[]> DataIn) {
            this.Data = DataIn;
            this.fireTableDataChanged();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;// length;
        }

        @Override
        public int getRowCount() {
            return Data.size();
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return Data.get(row)[col];

        }
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Content of CSV file: with "." that seems to bother :

CSV 文件内容:带“​​.” 这似乎很困扰:

Valeur par défaut,07/04/2014,0.5,1,0,0,0
Valeur par défaut,07/04/2014,0.5,1,0,0,0
Valeur par défaut,07/04/2014,0.5,1,0,0,0
Valeur par défaut,07/04/2014,0.5,1,0,0,0
Valeur par défaut,07/04/2014,0.5,1,0,0,0

采纳答案by Priyesh

You have done readLine twice. Once in the while condition and next inside it. You are losing the line read in the while condition.

您已经完成了两次 readLine。一旦进入 while 条件,然后进入其中。您正在丢失 while 条件中读取的行。

Updated:Changed the code to the following and it gives the expected output:

更新:将代码更改为以下内容,并提供预期的输出:

package stackoverflow;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;

public class T1Data extends JPanel {
    private final JTable table;

    public T1Data() {
        super(new BorderLayout(3, 3));
        this.table = new JTable(new MyModel());
        this.table.setPreferredScrollableViewportSize(new Dimension(700, 70));
        this.table.setFillsViewportHeight(true);
        JPanel ButtonOpen = new JPanel(new FlowLayout(FlowLayout.CENTER));
        add(ButtonOpen, BorderLayout.SOUTH);
        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        // Add the scroll pane to this panel.
        add(scrollPane, BorderLayout.CENTER);
        // add a nice border
        setBorder(new EmptyBorder(5, 5, 5, 5));
        CSVFile Rd = new CSVFile();
        MyModel NewModel = new MyModel();
        this.table.setModel(NewModel);
        File DataFile = new File("res.csv");
        ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);
        NewModel.AddCSVData(Rs2);
        System.out.println("Rows: " + NewModel.getRowCount());
        System.out.println("Cols: " + NewModel.getColumnCount());
    }

    // Method for reading CSV file
    public class CSVFile {
        private final ArrayList<String[]> Rs = new ArrayList<String[]>();
        private String[] OneRow;

        public ArrayList<String[]> ReadCSVfile(File DataFile) {
            try {
                BufferedReader brd = new BufferedReader(new FileReader(DataFile));
                while (brd.ready()) {
                    String st = brd.readLine();
                    OneRow = st.split(",|\s|;");
                    Rs.add(OneRow);
                    System.out.println(Arrays.toString(OneRow));
                } // end of while
            } // end of try
            catch (Exception e) {
                String errmsg = e.getMessage();
                System.out.println("File not found:" + errmsg);
            } // end of Catch
            return Rs;
        }// end of ReadFile method
    }// end of CSVFile class

    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("T1Data");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Create and set up the content pane.
        T1Data newContentPane = new T1Data();
        frame.setContentPane(newContentPane);
        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    class MyModel extends AbstractTableModel {
        private final String[] columnNames = { "1", "2", "3", "4", "5", "6", "7", "8" };
        private ArrayList<String[]> Data = new ArrayList<String[]>();

        public void AddCSVData(ArrayList<String[]> DataIn) {
            this.Data = DataIn;
            this.fireTableDataChanged();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;// length;
        }

        @Override
        public int getRowCount() {
            return Data.size();
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return Data.get(row)[col];
        }
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Updated:

更新:

Output: enter image description here

输出: 在此处输入图片说明

回答by Ordous

Your problem is in the whileloop inside the reader. You read a line, test if it is null, and since it isn't, you read and process the next line. Am I right in assuming you only see the second and fourth lines from your file? A better way to do it would be:

您的问题出while在读者内部的循环中。您读取一行,测试它是否为空,如果不是,则读取并处理下一行。我假设您只看到文件中的第二行和第四行是否正确?更好的方法是:

String st = brd.readLine();
while (st != null) {
    <do something>
    st = brd.readLine();
}

OR

或者

while ((String st = brd.readLine()) != null) {
    <do stuff>
}

(Second variant is generally discouraged)

(通常不鼓励第二种变体)

Also, the code above is full of malpractices (not closing resources, double model creation, inconsistent naming convention etc). I suggest you get someone to review it (or post to https://codereview.stackexchange.com/), unless you are aware of those and were just lazy to make a better example.

此外,上面的代码充满了弊端(未关闭资源、创建双模型、不一致的命名约定等)。我建议你找人(或发布到https://codereview.stackexchange.com/),除非你知道这些并且懒得举一个更好的例子。