简体   繁体   中英

Read/Write objects and lists to file

I want to write/read from a .txt file the attributes of my object. My main struggle is that my object has a Map<String, Object> which I'd like to write aswell. I'll try to explain it with examples:

I've got a Hospital, which has Departments, and every Department has Doctors. I want to be able to save the Hospital, but that also includes saving it's departments and the doctors in those departments, so the .txt file will be something like this:

So a Hospital has a Map<String, Department> and a Deparment has a Map<Integer, Doctor>

Hospital1

-Department1

--Doctors1

--Doctors2

-Department2

Which Hospital1 would write it's parameters like HospitalName-200-100 , and below that every Department from that Hospital, same with the Dpts and Docs.

To do so I've implemented those methods to write/read to a file. But I don't really know how could I implement the reading and storing to the objects.

I might not be clear enough, but I don't really know how to explain it in words. It's a problem when it comes to Reading what I've got in a txt file, since writting it in some way its fairly easy. So I guess, it would solve the problem if I could read it line by line? I don't really know, kinda lost here.

//WRITE
public void escriureText(String linia)
{        
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(f,true)))
    {
        bw.write(linia);
        bw.write("\r\n");
        bw.close();
    }
    catch (Exception e) 
    {
        throw new IllegalArgumentException(e);
    }
}


//READ
public String llegirText()
{
    String linia = "";
    String line = "";
    try (BufferedReader reader = new BufferedReader(new FileReader(f)))
    {
        while ((line = reader.readLine()) != null) 
        {
            linia = linia + line + "\n";
        }
    }
    catch (Exception e) 
    {
        throw new IllegalArgumentException(e);
    }
    return linia;
}

One solution would be to use xml format. The file would look something like this then.

<Hospital>
   <Department>
      <Doctor>
      </Doctor>
      <Doctor>
      </Doctor>
   </Department>
   <Department>
      <Doctor>
      </Doctor>
      <Doctor>
      </Doctor>
   </Department>
   <Department>
      <Doctor>
      </Doctor>
      <Doctor>
      </Doctor>
   </Department>
</Hospital>

To save the xml format you can use http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Document.html

code example for using xml can you find here. http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM