Search code examples
javalinked-listfilewriter

write(in file) only the last data in LinkedList


I am trying to write a file called movie.txt but unfortunately it only stored the last one in the LinkedList. What should I use to actually make it store all of them by line because I need it as input file after this.

import javax.swing.*;
import java.io.*;

public class movie508
{
    public static void main(String[] args) throws IOException
    {
        LinkedList listMovie = new LinkedList();
        int size = Integer.parseInt(JOptionPane.showInputDialog("Enter number of movie: "));
        Movie m;

        for(int i = 0; i < size; i++)
        {
            String a = JOptionPane.showInputDialog("Enter name : ");
            int b = Integer.parseInt(JOptionPane.showInputDialog("Enter year : "));
            String c = JOptionPane.showInputDialog("Enter LPF rating : ");
            int d = Integer.parseInt(JOptionPane.showInputDialog("Enter time"));
            String e = JOptionPane.showInputDialog("Enter genre : ");
            double f = Double.parseDouble(JOptionPane.showInputDialog("Enter member rating : "));

            m = new Movie(a, b, c, d, e, f);
            listMovie.insertAtFront(m);
        }

        Object data = listMovie.getFirst();
        PrintWriter out = null;

        while(data != null)
        {
            m = (Movie)data;

            try {

                out = new PrintWriter(new FileWriter("movie.txt"));
                out.write(m.toString());
            } 
            finally 
            {
                if (out != null) {
                    out.close();
                }
            }
            data = listMovie.getNext();
        }

    }}

Solution

  • You're reopening the file, and thus overwriting it, in each iteration of the while loop. Open it once before the loop, and close it at it's end:

    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileWriter("movie.txt"));
        while(data != null) {
            m = (Movie)data;
            out.println(m.toString());
            data = listMovie.getNext();
        }
    } 
    finally {
        if (out != null) {
            out.close();
        }
    }