Delirium_EA
Delirium_EA

Reputation: 7

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. After entering the values, the data is listed in a JList. Now I want to save the data from the JList into a Txt file. But I can't find a way to get the data from the 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.

Maybe there is even a better way to do this but I haven't found something.

Some tips would be helpful :)

Upvotes: 0

Views: 939

Answers (3)

Ilvis Faulbaums
Ilvis Faulbaums

Reputation: 21

I made this code with comments for jButton and jList in jFrame, Button saves text Items to File from 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

Upvotes: 1

Victor
Victor

Reputation: 3978

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.

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, a.k.a. 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.

Upvotes: 1

camickr
camickr

Reputation: 324118

There is no JList method that does this for you.

You need to get the data from the ListModel.

You get the ListModel from the JList using the getModel() method.

You need to write a loop to:

  1. get each element from the ListModel using the getElementAt(...) method.
  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. 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.

Upvotes: 2

Related Questions