I need to save the linked list I created to a file but I want each part of the users account to be its own element. i.e. (username, password, email, name, breed, gender, age, state, hobby). Something is wrong with my code however and each account is its own element. Any help would be great!
Also here is a link to my Account Class which is used to create the Linked List
http://pastebin.com/jnBrcnP1
Linked List looks like this:
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
Saves to file like this:
tobitobi123tobi@hotmail.comtobiMixed BreedMale1-2VirginiaWalking
peppypeppy123peppy@hotmail.compeppyChihuahuaMale5-6VirginiaEating
Code for creating Linked List:
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);
}
}
Code for Saving Linked List to file:
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) {
}
This is the problem, in
Account:You’re assuming that
\nis the appropriate line ending. My guess is you’re running on Windows, where it would be\r\n. Personally, I think it would be better for your “writing” code not to usetoString()at all, but to write out the lines itself – after all, it knows the format it wants to use.(Additionally, I would advise against using
"" + ...as a way of converting a value into a string…)