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?
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?
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:
StandardCharsets.UTF_8 and explicit Path to avoid encoding/path issues. IOException and, if using invokeAndWait, InterruptedException/InvocationTargetException. 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);We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.