How to write XML file with Java and read it?

How do I read from TreeSet and write it to a file in Java? What is the code?

  • Should I use BufferedReader and BufferedWriter for it? My code is: Set<String> s1=new TreeSet<String>( ); s1.add(name); s1.add(gender); s1.add(dob); How can I write this information from TreeSet to File?

  • Answer:

    If you want to to create a "text" file with your String content, then create a BufferedWriter, iterate through the TreeSet with a for statement and write each line. To read it back, use a BufferedReader, readLine, and add() to the set. If you want to create a "binary" file, then you can use serialisation with ObjectOutputStream and ObjectInputStream. This can deal with any set content that is Serializable, and not only String or char.

Miguel Paraz at Quora Visit the source

Was this solution helpful to you?

Other answers

Use PrintWriter like in this method here :  public static void print(String file, Set<String>set) throws Exception{         PrintWriter out = new PrintWriter(new FileWriter(new File(file)));               for(String s: set){                        out.println(s);              }               out.close();  }

Alket Cecaj

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.