如何从TreeSet读取内容并写入文件?

时间:2014-01-26 12:06:54

标签: java data-structures

我的代码是:

Set<String> s1=new TreeSet<String>();
   s1.add(name);
   s1.add(gender);
   s1.add(dob);

如何读取这些变量并将其写入文件?我应该使用Buffered Reader和Buffered Writer吗?

3 个答案:

答案 0 :(得分:1)

请尝试以下代码

public class SetWriter {

public static void main(String[] args) throws FileNotFoundException, IOException {
    String name = "Muhammad", gender = "male", dob = "8/feb/1992";
    Set<String> s1 = new TreeSet<>();
    s1.add(name);
    s1.add(gender);
    s1.add(dob);
    File f = new File("D:\\east.txt");
    f.createNewFile();
    FileWriter fw = new FileWriter(f);
    for (String s: s1) {
        fw.write(s+"\r\n");
    }
    fw.close();
}

}

答案 1 :(得分:0)

使用围绕FileWriter的BufferedWriter。迭代集合的元素并将每个元素写入BufferedWriter。确保关闭作者。

答案 2 :(得分:-2)

字符串是可序列化的,因此您只需通过JXB即可完成。或者更简单的阅读http://www.tutorialspoint.com/java/java_serialization.htmhttp://www.vogella.com/tutorials/JavaSerialization/article.html