将链接列表保存到单独行上的文件中

时间:2012-03-12 11:49:39

标签: java io linked-list

我会尽量保持这一点。基本上我有一个链接的数据列表,其中每个元素都在一个单独的行上。但是,当我尝试将其保存到文件时,它只是在一个长字符串中链接在一起。我需要它保存到不同行的文件,因为我必须多次读取并保存到该文件,并且我读取文件的方式一切都必须在单独的行上。 谢谢!

将链接列表保存到文件的代码:

        String file_name = "output.txt";
        try {

                FileWriter fstream = new FileWriter(file_name);
                BufferedWriter out = new BufferedWriter(fstream);

                ListIterator itr = account.listIterator();
                while (itr.hasNext()) {
                    Account element = (Account) itr.next();
                    out.write(element + "\n");
                }

                out.close();
                System.out.println("File created successfully.");

        } catch (Exception e) {
        }

创建链接列表的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Main extends javax.swing.JFrame implements ActionListener{

public static String readLine(BufferedReader br) throws IOException {
    String rl = br.readLine();
    if (rl.trim().length() > 2){
        return rl;
    }else return readLine(br);
}

public static void main(String[] args) {

    LinkedList<Account> account = new LinkedList<Account>();

    try
    {
        read(account, "output.txt");
    } catch (Exception e)
    {
        System.err.println(e.toString());
    }
        display(account);
    }

    public static void read(LinkedList<Account> account, String inputFileName) throws java.io.IOException
    {
        BufferedReader infile = new BufferedReader(new FileReader(inputFileName));
        while(infile.ready())
        {

            String username = readLine(infile);
            String password = readLine(infile);
            String email = readLine(infile);
            String name = readLine(infile);
            String breed = readLine(infile);
            String gender = readLine(infile);
            String age = readLine(infile);
            String state = readLine(infile);
            String hobby = readLine(infile);

            Account a = new Account(username, password, email, name, breed, gender, age, state, hobby);
            account.add(a);
            a.showList();
        }
        infile.close();
    }

    public static void display(LinkedList<?> c)
    {
        for (Object e : c)
        {
            System.out.println(e);
        }
    }

3 个答案:

答案 0 :(得分:1)

使用PrintWriter(String fileName).println(...)。避免文字\n

答案 1 :(得分:1)

相反,

out.write(element + "\n");

out.write(element);
out.newLine();

参考newLine()方法的javadoc:

  

写一个行分隔符。行分隔符字符串由。定义   系统属性line.separator,并不一定是单一的   换行符('\ n')字符。

所以,对于新行,\ n似乎并不正确。

答案 2 :(得分:0)

在您写入文件的每个Account之后会有一个换行符。

    Account element = (Account) itr.next();
    out.write(element + "\n");

我怀疑真正的问题在于Account.toString()方法。鉴于您阅读它的方式,您需要确保在帐户对象的每个字段后面都有换行符。

相关问题