只写(在文件中)LinkedList中的最后一个数据



我试图写一个名为movie.txt的文件,但不幸的是它只存储了LinkedList中的最后一个。我应该用什么来使它按行存储它们呢?因为我需要它作为输入文件。

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();
        }
    }}

while循环的每次迭代中重新打开文件,从而覆盖它。在循环开始前打开它一次,并在循环结束时关闭它:

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();
    }
}
In java FileWriter api is as below:
public FileWriter(String fileName,
          boolean append)
           throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning. 
Throws: 
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
So if you want to append just make the append parameter true as below:
out = new PrintWriter(new FileWriter("movie.txt",true));
This will append the text to existing file instead of over writing.

相关内容

  • 没有找到相关文章

最新更新