Java-Gaming.org Hi !
Featured games (81)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (576)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Read/Write ArrayList to/from file  (Read 3040 times)
0 Members and 2 Guests are viewing this topic.
Offline alaslipknot
« Posted 2013-06-05 01:20:05 »

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 :
1  
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

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Offline wreed12345

JGO Knight


Medals: 25
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #1 - Posted 2013-06-05 01:24:20 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
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.

Offline alaslipknot
« Reply #2 - Posted 2013-06-05 01:36:28 »

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  Roll Eyes ??

thank you

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline wreed12345

JGO Knight


Medals: 25
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #3 - Posted 2013-06-05 01:38:58 »

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.

Offline SHC
« Reply #4 - Posted 2013-06-05 01:40:37 »

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.

Offline alaslipknot
« Reply #5 - Posted 2013-06-05 01:43:03 »

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.
no no  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


"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Offline actual

JGO Coder


Medals: 23



« Reply #6 - Posted 2013-06-05 02:54:23 »

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.
Offline alaslipknot
« Reply #7 - Posted 2013-06-05 03:04:47 »

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  Undecided

this is my writing method :
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
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<Condidat>

thank you very much

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Offline SHC
« Reply #8 - Posted 2013-06-05 04:09:13 »

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

Offline wreed12345

JGO Knight


Medals: 25
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #9 - Posted 2013-06-05 18:32:47 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
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();
         }
      }

http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

this looks like it will help

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #10 - Posted 2013-06-05 20:22:04 »

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 Smiley

So if you write the file you do this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
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 Smiley

The file would look something like this:


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

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline Sammidysam
« Reply #11 - Posted 2013-06-05 20:37:35 »

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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
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
1  
2  
3  
4  
5  
6  
7  
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
1  
2  
3  
4  
5  
6  
7  
8  
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.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (37 views)
2014-10-17 03:59:02

Norakomi (28 views)
2014-10-16 15:22:06

Norakomi (24 views)
2014-10-16 15:20:20

lcass (27 views)
2014-10-15 16:18:58

TehJavaDev (52 views)
2014-10-14 00:39:48

TehJavaDev (54 views)
2014-10-14 00:35:47

TehJavaDev (42 views)
2014-10-14 00:32:37

BurntPizza (64 views)
2014-10-11 23:24:42

BurntPizza (36 views)
2014-10-11 23:10:45

BurntPizza (77 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!