我正在尝试编写一个名为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();
}
}}
答案 0 :(得分:0)
您在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();
}
}
答案 1 :(得分:0)
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.