Hi Guys,

How to write the contents of JList into a text file. i have a JList and i want to add the list elements to a text file.
How to do this?

Dani AI

Generated

Short answer for : read the JList model and write each element to a file. Decide first whether you want every element or only the selected ones, and whether the list holds plain strings or custom objects (if custom objects, pick the property you want to persist instead of relying on toString). As pointed out, brushing up on Java I/O is useful; below are compact, practical examples plus notes on threading and common pitfalls.

Example — write every element (uses NIO + try-with-resources, Java 7+):

ListModel<?> model = myList.getModel();
Path out = Paths.get("list.txt");
try (BufferedWriter bw = Files.newBufferedWriter(out, StandardCharsets.UTF_8)) {
    for (int i = 0; i < model.getSize(); i++) {
        Object item = model.getElementAt(i);
        bw.write(item == null ? "" : item.toString());
        bw.newLine();
    }
}

Example — write only selected items (convenient API):

List<?> selected = myList.getSelectedValuesList();
Path out = Paths.get("selected.txt");
try (BufferedWriter bw = Files.newBufferedWriter(out, StandardCharsets.UTF_8)) {
    for (Object o : selected) {
        bw.write(o == null ? "" : o.toString());
        bw.newLine();
    }
}

Important notes and troubleshooting:

  • Access the model on the Event Dispatch Thread (EDT). If you need to grab data from another thread, take a short snapshot on the EDT and then do the file I/O off the EDT to avoid freezing the UI (example below).
  • Use StandardCharsets.UTF_8 and explicit Path to avoid encoding/path issues.
  • Handle IOException and, if using invokeAndWait, InterruptedException/InvocationTargetException.
  • If list items are custom objects, map them to the exact string you want written (for example myObj.getName()), rather than depending on toString().

Snapshot-on-EDT pattern (safe for background write):

List<String> snapshot = new ArrayList<>();
SwingUtilities.invokeAndWait(() -> {
    ListModel<?> m = myList.getModel();
    for (int i = 0; i < m.getSize(); i++) snapshot.add(String.valueOf(m.getElementAt(i)));
});
// write 'snapshot' to file off the EDT
Files.write(Paths.get("list.txt"), snapshot, StandardCharsets.UTF_8);

have you already solved it? if not, why did you mark it solved?
I assume you know how to get the contents from the JList, so your problem must lie in the writing to the txt file part.

this is a good place to start reading up on that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.