Read/Write ArrayList to/from file

Hello everyone,

supposing that i have a class called “Student” that contain multiple fields (name,age,section, marks)
and i have an ArrayList of students called list , so every case of the list will contain a student, which mean i can do something like this for example :

System.out.println(list.get(0).name);

this will print the name of the student in the case 0
what i can’t do is,
how can i write that list into a text file ?
i thought about converting each field of the list into a string then write it into the file, but if i do that i will find a little trouble while retrieving the list, cause i need that every case of the list be a “Student” so i can use it in other things,
i thought about a solution like writing a star (*) before writing the list, then convert each field to string,then write another star and then when i want to retrieve depending on the line after the 1st star i will cast that element to each original type
but i don’t think am the only one who needed to write a whole type into a file so i think it must be a better solution for this

thank you


try {
			File file = new File("/users/username/filename.txt");
 
		   // if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
 
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
                        //set this to the string you are trying to write
			bw.write(line.get(0).name);
			bw.close();
 
		} catch (IOException e) {
			e.printStackTrace();
		}

Then after you write everything with a new line after each string, read it and set the values with a buffered reader

EDIT:
I think xml may be your best option, it will help keep things organized and readable.

i never used it, is it hard to get starting with it ? and do you have a good link for that ::slight_smile: ??

thank you

Are you using libgdx by any chance? It makes it so much easier. If you’re not I have no suggestions. I think I would like to learn more about java and xml too.

A link for you on Stackoverflow. They say Dom4J is the best but I’ve never used XML. I’ll prefer to use the good old INI format since I can write my own INI parser.

no no :stuck_out_tongue:
am still working on this program i thought maybe this can be useful for someone else during a game development that’s why i post it here

@SHC
thanx

Are you writing to the file because you want to view the file, or is it just a way of storing things on disk? If it’s the latter, then you may want to look up object serialization.

actually both,
am creating a “data base” program, everything i have must be stored in the file and i found a way to do that (it may be “dump” but it works) now i don’t know how to “read” those information :-\

this is my writing method :


public void store(ArrayList<Condidat> list, int i) {
		try {
			File file = new File("d:/condidats.txt");

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);

			// <cond> </cond> = begin and end of a list //
			// <date> </date> = begin and end of the date arrayList inside the
			// list //
			// <hours> </hours> = begin and end of the hours arrayList inside
			// the list //
			bw.newLine();
			bw.write("<cond>");
			// add simple information
			bw.newLine();
			bw.write(list.get(i).getName());
			bw.newLine();
			bw.write(Integer.toString(list.get(i).getTotalHours()));
			bw.newLine();
			bw.write(Double.toString(list.get(i).getTheory()));
			bw.newLine();
			bw.write(Double.toString(list.get(i).getAdvance()));
			bw.newLine();
			bw.write(Double.toString(list.get(i).getHourPrice()));
			bw.newLine();
			bw.write(Double.toString(list.get(i).getRemain()));
			bw.newLine();
			bw.write(list.get(i).getExamDate());
			bw.newLine();
			bw.write(Double.toString(list.get(i).getTotal()));

			// add hours and date information
			bw.newLine();
			bw.write("<date>");
			for (int j = 0; j < list.get(i).getDayDate().size(); j++) {
				bw.newLine();
				bw.write("<hours>");
				bw.newLine();
				bw.write(list.get(i).getDayDate().get(j));
				bw.newLine();
				bw.write(Integer.toString(list.get(i).getHourInDate().get(j)));
				bw.newLine();
				bw.write("<hours>");
			}
			bw.newLine();
			bw.write("</date>");

			bw.newLine();
			bw.write("</cond>");

			bw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

can you please help me on creating a method that read a file (created by the store method) and return an ArrayList

thank you very much

Uploaded the INI Parser to GitHub. You can see it here. https://github.com/sriharshachilakapati/JINI

BufferedReader br = null;
 
		try {
 
			String sCurrentLine;
 
//file to read
			br = new BufferedReader(new FileReader("C:\\testing.txt"));
 
			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}



this looks like it will help

If you’re doing it like that (manually writing “<something></something>”) then don’t use xml.
For simple tasks xml is really too cracy. Toooo cracy. And it’s also slow.
And it stinks… sometimes…

Anyways, what you might be looking for would be a really simple format like CSV, which is an abbreviation for “Comma-Seperated-Values”, which already explains almost everything :slight_smile:

So if you write the file you do this:


public void store(Candidat candidat, BufferedWriter writer) {
    writeCommaSeperatedLine(writer,
        Double.toString(candidat.getTotalHours()),
        Double.toString(candidat.getTheory()),
        Double.toString(candidat.getAdvance()),
        Double.toString(candidat.getHourPrice()),
        Double.toString(candidat.getRemain()),
        candidat.getExamDate(),
        Double.toString(candidat.getTotal())
    );
}

// Probably rename ^^
public void writeCommaSeperatedLine(BufferedWriter writer, String... values) {
    for (int i = 0; i < values.length; i++) {
        writer.write(values[i]);
        if (i-1 != values.length) writer.write(",");
    }
}

public Candidat readFromStore(BufferedReader reader) {
    String[] csv = readCommaSeperatedLine(reader);
    if (csv.length != 7) { // 7 == the number of saved comma-seperated values
        // throw some kind of error
        // Don't do the following:
        return null;
    } else {
        return new Candidat()
            .setTotalHours(Double.parseDouble(csv[0])) // Double.parseDouble can throw an error: NumberFormatException
            .setTheory(Double.parseDouble(csv[1]))
            .setAdvance(Double.parseDouble(csv[2]))
            .setHourPrice(Double.parseDouble(csv[3]))
            .setRemain(Double.parseDouble(csv[4]))
            .setExamDate(csv[5])
            .setTotal(Double.parseDouble(csv[6]));
    }
}

// Probably rename, too ^^
public String[] readCommaSeperatedLine(BufferedReader reader) {
    String line = reader.readLine();
    return line.split(",");
}

Hope, this helps you :slight_smile:

The file would look something like this:

125.0,3.0,5.0,14.52,55.1,15.10.13,1101.0 ...

How about JSON? You can use the minimal-json library which is supposedly very fast and then you can create a configuration like this:

writing to file


JsonObject students = new JsonObject();
JsonObject John = new JsonObject();
John.add("Total Hours", getTotalHours());
John.add("Theory", getTheory());
John.add("Advance", getAdvance());
John.add("Hour Price", getHourPrice());
John.add("Remain", getRemain());
John.add("Exam Date", getExamDate());
John.add("Total", getTotal());
students.add("John", John);
students.writeTo(new FileWriter("students.json", false));

reading from file


FileInputStream fstream = new FileInputStream("students.json");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
JsonObject students = JsonObject.readFrom(br);
JsonObject John = students.get("John");
double totalHours = John.get("Total Hours").asDouble();
String examDate = John.get("Exam Date").asString();

new student


FileInputStream fstream = new FileInputStream("students.json");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
JsonObject students = JsonObject.readFrom(br);
JsonObject newKid = new JsonObject();
newKid.add("Exam Date", getExamDate());
students.add("New Guy", newKid);
students.writeTo(new FileWriter("students.json", false));

It’s not too hard at all.