简体   繁体   English

将 JList 保存到 Txt 文件中

[英]Save JList into Txt File

After searching for an answer for hours I decided to ask it here, since the solutions I found didn't work.在搜索了几个小时的答案后,我决定在这里提问,因为我找到的解决方案不起作用。

I have a simple GUI to register a persons first/last name and date of birth.我有一个简单的 GUI 来注册一个人的名字/姓氏和出生日期。 After entering the values, the data is listed in a JList.输入值后,数据将列在 JList 中。 Now I want to save the data from the JList into a Txt file.现在我想将 JList 中的数据保存到 Txt 文件中。 But I can't find a way to get the data from the JList.但是我找不到从 JList 获取数据的方法。

public void save(){
    try(BufferedWriter bw = new BufferedWriter(new FileWriter("jlist.txt")))
    {
        /* Here should be the part, where I get the data from the JList */

        bw.write(person.getNachname() + " ; " + person.getVorname() + " ; " + person.getDate() + "\n");
    } catch (Exception speichern) {
        speichern.printStackTrace();
    }
}

Later I want to take the created Txt file and load it back into the same JList.稍后我想将创建的 Txt 文件加载回同一个 JList。

Maybe there is even a better way to do this but I haven't found something.也许有更好的方法可以做到这一点,但我还没有找到。

Some tips would be helpful :)一些提示会有所帮助:)

There is no JList method that does this for you.没有 JList 方法可以为您执行此操作。

You need to get the data from the ListModel .您需要从ListModel获取数据。

You get the ListModel from the JList using the getModel() method.您可以使用getModel()方法从JList获取ListModel

You need to write a loop to:你需要写一个循环:

  1. get each element from the ListModel using the getElementAt(...) method.使用getElementAt(...)方法从ListModel获取每个元素。
  2. convert the element to a String and write the data to your file.将元素转换为字符串并将数据写入文件。

Some tips would be helpful一些提示会有所帮助

Not related to your question, but typically data like this would be displayed in a JTable.与您的问题无关,但通常这样的数据会显示在 JTable 中。 Then you have a separate column for each of the first name, last name and date.然后你有一个单独的列用于每个名字、姓氏和日期。 Read the section from the Swing tutorial on How to Use Tables for more information.阅读 Swing 教程中关于如何使用表的部分以获取更多信息。

As camickr point out there is no method implemented for what you a trying to achieve, instead there is a combination of things that you could do for archiving your goal.正如 camickr 所指出的,没有为您想要实现的目标而实施的方法,相反,您可以通过组合来实现目标。

You are facing the problem of data persistence .您正面临数据持久性的问题。 In now-a-days for small|medium|big size industrial applications the recommended approach is to relay on databases.在当今的小型|中型|大型工业应用程序中,推荐的方法是中继数据库。 I guess that is out the scope for one person that is starting to code, so using files for storing info is OK but is not straightforward.我想这超出了开始编码的人的范围,因此使用文件存储信息是可以的,但并不简单。

In your case, if your application is for non-commercial purposes I would suggest to use the default mechanism for serializing and deserializing objects that comes bundled with the platform.在您的情况下,如果您的应用程序用于非商业目的,我建议使用默认机制来序列化和反序列化与平台捆绑在一起的对象。 With this you could write an entire object (including its data, aka its state ) to a file on a disk, and later retrieve it with few lines codes.有了这个,你可以将整个对象(包括它的数据,也就是它的状态)写入磁盘上的文件,然后用几行代码检索它。 There are details about how the object gets serialize ("translate object to bits") and deserialized ("translate bits to object") that doesn't comes into place right now, but is well to advice to study them in the future if you planning to use this method in a commercial application.有关于对象如何序列化(“将对象转换为位”)和反序列化(“将位转换为对象”)的详细信息,目前还没有实现,但是如果您将来研究它们,建议您计划在商业应用中使用这种方法。

So I suggest that you load and store the information of your application on start-up and shutdown respectively, thus only one load and store per application instance, while the application is active work with the data on memory.所以我建议你分别在启动和关闭时加载和存储应用程序的信息,这样每个应用程序实例只加载和存储一次,而应用程序在活动时处理内存中的数据。 THIS is the simplest approach you could have in any application, and for that reason I suggest to start with this ideal scenario.这是您可以在任何应用程序中使用的最简单的方法,因此我建议从这个理想的场景开始。

So, I say a lot of things but let's goes to the code that shows an example of storing (serialize) and loading (deserialize)所以,我说了很多,但让我们来看一下显示存储(序列化)和加载(反序列化)示例的代码

import java.io.*;
import java.util.*;

class Person implements Serializable {
  String name;
  int birthDate;

  public Person(String name, int birthDate) {
    this.name = name;
    this.birthDate = birthDate;
  }
}

class Main {
  public static void main(String[] args) {
     Collection<Person> collection = createExampleCollection();
     System.out.println(collection);
     storeCollection(collection, "persons.data");
     Collection<Person> otherCollection = loadCollection("persons.data");
     System.out.println(otherCollection);
  }

  private static Collection<Person> createExampleCollection()  {
        Collection<Person> collection = new ArrayList<Person>();

        collection.add(new Person("p1",0));
        collection.add(new Person("p2",10));
        collection.add(new Person("p2",20));
        return collection;
  }


  // here I'm doing two separated things that could gone in separate functions, 1) I'm converting into bytes and object of an specific class, 2) saving those bytes into a file on the disk. The thing is that the platform offers us convenient objects to do this work easily
  private static void storeCollection(Collection<Person> collection, String filename) {
     try {
         FileOutputStream fos = new FileOutputStream(filename); 
         ObjectOutputStream out = new ObjectOutputStream(fos);
         out.writeObject(collection);
         out.close();
         fos.close();
      } catch (IOException i) {
         i.printStackTrace();
      }
  }

  // again there two things going on inside, 1) loading bytes from disk 2) converting those bits into a object of a specific class.
  private static Collection<Person> loadCollection(String filename) {
      try {
         FileInputStream fis = new FileInputStream(filename);
         ObjectInputStream in = new ObjectInputStream(fis);
         Collection<Person> persons = (Collection<Person>) in.readObject();
         in.close();
         fis.close();
         return persons;
      } catch (Exception i) {
         i.printStackTrace();
         return null;
      }

  }
}

You should try to use the functions of loadCollection and storeCollection on start-up and shutdown respectively.您应该尝试分别在启动和关闭时使用 loadCollection 和 storeCollection 功能。

I made this code with comments for jButton and jList in jFrame, Button saves text Items to File from jList.我用 jFrame 中的 jButton 和 jList 注释制作了这段代码,Button 将文本项从 jList 保存到文件。

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) { //jButton name: "btnSave"                                      
    try {                                                                   //trying to save file
        BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt")); //file where I store the data of jList1    (file will be stored at: C:\Users\%username%\Documents\NetBeansProjects\<ThisProjectName>\data.txt) (if You use NetBeans)
        for (int i=0; i<jList1.getModel().getSize(); i++){                  //opens a cycle to automatically store data of all items            
        bw.write(jList1.getModel().getElementAt(i));                        //writing a line from jList1             
        bw.newLine();                                                       //making a new line for the next item (by removing this line, You will write only one line of all items in file)
        }                                                                   //cycle closes
        bw.close();                                                         //file writing closes
    } catch (IOException ex) {                                              //catching the error when file is not saved
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); //showing the error
    }                                                                       //Exception closes        
}                                                                           //Action closes

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

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