[英]Save JList into Txt File
在搜索了几个小时的答案后,我决定在这里提问,因为我找到的解决方案不起作用。
我有一个简单的 GUI 来注册一个人的名字/姓氏和出生日期。 输入值后,数据将列在 JList 中。 现在我想将 JList 中的数据保存到 Txt 文件中。 但是我找不到从 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();
}
}
稍后我想将创建的 Txt 文件加载回同一个 JList。
也许有更好的方法可以做到这一点,但我还没有找到。
一些提示会有所帮助:)
没有 JList 方法可以为您执行此操作。
您需要从ListModel
获取数据。
您可以使用getModel()
方法从JList
获取ListModel
。
你需要写一个循环:
getElementAt(...)
方法从ListModel
获取每个元素。一些提示会有所帮助
与您的问题无关,但通常这样的数据会显示在 JTable 中。 然后你有一个单独的列用于每个名字、姓氏和日期。 阅读 Swing 教程中关于如何使用表的部分以获取更多信息。
正如 camickr 所指出的,没有为您想要实现的目标而实施的方法,相反,您可以通过组合来实现目标。
您正面临数据持久性的问题。 在当今的小型|中型|大型工业应用程序中,推荐的方法是中继数据库。 我想这超出了开始编码的人的范围,因此使用文件存储信息是可以的,但并不简单。
在您的情况下,如果您的应用程序用于非商业目的,我建议使用默认机制来序列化和反序列化与平台捆绑在一起的对象。 有了这个,你可以将整个对象(包括它的数据,也就是它的状态)写入磁盘上的文件,然后用几行代码检索它。 有关于对象如何序列化(“将对象转换为位”)和反序列化(“将位转换为对象”)的详细信息,目前还没有实现,但是如果您将来研究它们,建议您计划在商业应用中使用这种方法。
所以我建议你分别在启动和关闭时加载和存储应用程序的信息,这样每个应用程序实例只加载和存储一次,而应用程序在活动时处理内存中的数据。 这是您可以在任何应用程序中使用的最简单的方法,因此我建议从这个理想的场景开始。
所以,我说了很多,但让我们来看一下显示存储(序列化)和加载(反序列化)示例的代码
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;
}
}
}
您应该尝试分别在启动和关闭时使用 loadCollection 和 storeCollection 功能。
我用 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.