【问题标题】:How to load records into a jTable from a file?如何将记录从文件加载到 jTable 中?
【发布时间】:2016-04-08 13:24:47
【问题描述】:

我正在使用 netbeans 制作一个 GUI 程序,它应该是一个用于管理音像店记录的界面。

这是界面。这是两个选项卡,一侧允许人们添加记录,而另一个选项卡显示它们。当一个人添加记录时,它们会被添加到一个名为 output 的 .dat 文件中。我想将 .dat 文件用作视频记录的永久存储区域,基本上我想要发生的是,当加载 GUI 类时,程序会从 .dat 文件加载所有记录。我已经创建了我的代码,但出现以下错误:

run:
java.io.EOFException
    at java.io.RandomAccessFile.readChar(RandomAccessFile.java:773)
    at videostore.BinaryFile.getString(BinaryFile.java:82)
    at videostore.BinaryFile.load(BinaryFile.java:116)
    at videostore.VideoStore.main(VideoStore.java:409)
Exception in thread "main" java.lang.NullPointerException
    at videostore.VideoStore.main(VideoStore.java:420)
/Users/(my Name)/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)

然后我将所有相关代码粘贴到下面。

在GUI类的main方法中,名为VideoStore.java:

file = new BinaryFile("/Users/hanaezz/Desktop/output.dat");
        int length = file.length();
        int ID = 1;

        for (int xx = 0; xx < length; xx += file.getRecordLength()) {
            Video load = file.load(xx);
            String tempName = load.getVideoName();
            String tempProd = load.getProducer();
            String tempRat = load.getRating();
            String tempGenre = load.getGenre();
            short tempNum = load.getVidNum();
            float tempPrice = load.getvideoPrice(); 

            Object[] row = {ID, tempName, tempProd, tempGenre, tempRat, tempNum, tempPrice};


            model.addRow(row);

            ID++;
        }

VideoStore 构造函数类中:

public VideoStore() {
        initComponents();
        model = (DefaultTableModel) displayVideos.getModel();
    }

BinaryFile 类中:

private static final int RecordLength = 112;
public static Video load(int place){
        String name = "", prod="", rat="", genre="";

        float price = 1;
        short number = 1;
        try {
            raf.seek(place);
            name = getString(20);
            prod = getString(15);
            rat = getString(20);
            genre = getString(10);
            price = Float.parseFloat(getString(4));
            number = Short.parseShort(getString(4));

            writeString(20, name);
            writeString(15, prod);
            writeString(10, genre);
            writeString(4, VideoStore.vPrice.getText());
            writeString(4, VideoStore.vNumber.getText());
            writeString(4, rat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Video r = new Video(name, prod, genre, rat, number, price);
        return r;
    }

    public static int getRecordLength() throws IOException{
        return RecordLength;
    }

    public static int length() throws IOException {
        return (int)raf.length();
        }

最后,我的视频课:

    private static String videoName;
    private static String producer;
    private static String rating;
    private static String genre;
    private static short videoNumber;
    private static float videoPrice;

public Video(String a, String b, String c, String d, short e, float f){
    videoName = a;
    producer = b;
    rating = c;
    genre = d;
    videoNumber = e;
    videoPrice = f;
}

...然后是类中每个变量的 mutator 和 accessor 方法...

@Override
public String toString(){
    return videoName + "\t" + producer +
            "\t" + rating + "\t" + genre +
            "\t" + videoNumber + "\t" + videoPrice;
}

是的,我的问题是我不知道如何将文件中的记录加载到表中。在我的代码中,我尝试使用一个循环,该循环将根据记录的大小遍历文件中的每条记录。但是它似乎没有用。如果有人想查看我的完整代码或需要更多信息,请随时与我联系 :)

【问题讨论】:

标签: java swing io randomaccessfile eofexception


【解决方案1】:

首先,您应该使用更面向对象的方法。

您的视频类只包含静态属性,此时它应该如下所示:

public class Video implements Serializable{

    private String name;
    private String producer; //consider using an object for this
    private String rating; //consider using a numeric type for this
    private String genre; //consider using an object for this
    private int number;
    private double price;


    //getters and setters

}

检查Object-Oriented Programming Concepts

要添加新视频,您需要从图形界面获取用户输入,并使用它来创建视频对象。

Video video = new Video();

video.setName(nameTextField.getText());
//same for the other attributes

然后您可以将所有视频保存在List

List<Video> videosList = new ArrayList<>();

videoList.add(video);

然后你可以serialize你的列表到一个文件。

try(FileOutputStream outputFile = new FileOutputStream("/path/to/file");
    ObjectOutputStream out = new ObjectOutputStream(outputFile)){

      out.writeObject(videoList);

} catch (IOException e1) {

      // Handle the exception

}

要从文件中读取您的列表,您需要对其进行反序列化:

try(FileInputStream inputFile = new FileInputStream("/path/to/file");
    ObjectInputStream in = new ObjectInputStream(inputFile)){

      videoList = (List<Video>)in.readObject();

} catch (IOException e1) {

      // Handle the exception

}

【讨论】:

  • 感谢您的帮助!但是我不确定这是否能回答我的问题......一旦我重新启动程序,如何将文件加载回 jTable?
  • @Hanalei:这取决于您如何编写文件。如果您按照 Jefferson Lima 的说明进行操作,则可以读取文件并对其进行反序列化。
  • @GilbertLeBlanc 好的.. 但是如果我将所有对象序列化到一个文件中,那么这不会让我很难取消序列化并将其反馈回表中吗?编译器会知道如何区分不同的对象吗?
  • @Hanalei:尝试序列化视频对象列表,然后反序列化列表。编写序列化代码的人非常聪明。
  • 我添加了一个如何序列化和反序列化列表的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 2017-11-29
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多