我需要将我创建的链接列表保存到一个文件中,但是我希望用户帐户的每个部分都是它自己的元素。即(用户名、密码、电子邮件、姓名、品种、性别、年龄、状态、爱好)。但是,我的代码有问题,每个帐户都有自己的元素。任何帮助都会很好!
这里还有一个指向my类的链接,用于创建链接列表http://pastebin.com/jnBrcnP1
链接列表如下所示:
tobi
tobi123
tobi@hotmail.com
tobi
Mixed Breed
Male
1-2
Virginia
Walking
peppy
peppy123
peppy@hotmail.com
peppy
Chihuahua
Male
5-6
Virginia
Eating保存为这样的文件:
tobitobi123tobi@hotmail.comtobiMixed BreedMale1-2VirginiaWalking
peppypeppy123peppy@hotmail.compeppyChihuahuaMale5-6VirginiaEating创建链接列表的代码:
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);
}
}将链接列表保存到文件的代码:
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);
out.newLine();
}
out.close();
System.out.println("File created successfully.");
} catch (Exception e) {
}发布于 2012-03-13 22:32:07
这就是Account中的问题
public String toString() {
return ""+username+"\n"+password+"\n"+email+"\n"+name+
"\n"+breed+"\n"+gender+"\n"+age+"\n"+state+"\n"+hobby;
}您假设\n是适当的行尾。我猜你是在Windows上运行的,它就是\r\n。就我个人而言,我认为您的“编写”代码最好不要使用toString(),而是自己写行--毕竟,它知道它想要使用的格式。
(此外,我将劝阻使用"" + ...作为将值转换为字符串的一种方法.)
https://stackoverflow.com/questions/9693172
复制相似问题