创建类的实例并导出到文件

时间:2014-07-23 01:28:39

标签: java file class instance

如何创建类实例然后将其导出到文件?希望你能帮忙。这是我的代码:

import java.io.*;

public class Testing {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Testing t = new Testing();

    String fileName = ("C:/Users/Brandon/Desktop/Java/copy.java");

     try {
            FileWriter fileWriter =
                new FileWriter(fileName);

            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            bufferedWriter.write(t);

            bufferedWriter.close();
        }
        catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileName + "'");

我收到此错误消息:

  

BufferedWriter类型中的write(int)方法不适用于参数(Testing)。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您不能只是将Java对象写入文件。执行此操作的过程称为序列化,它对对象强加了某些要求。查看ObjectOutputStreamSerializable即可开始使用。

答案 1 :(得分:0)

这是您的代码可能正在寻找该部分的方式:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Testing implements Serializable {

private static final long serialVersionUID = 1L;

public static void main(String args[]) {
    Testing t = new Testing();
    String fileName = new String("copy.ser");
    t.write(t, fileName);
}

public void write(Testing t, String fileName) {

    try {

        FileOutputStream fout = new FileOutputStream("copy.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(t);
        oos.close();
        System.out.println("Done");

    } catch (Exception ex) {
        System.out.println(
            "Error writing to file '"
            + fileName + "'");
    }
}
}