将Java对象写入文件

Mar*_*ski 4 java binary file persistent-storage

是否可以将Java中的对象写入二进制文件?我想写的String对象是2个对象数组.我想这样做的原因是保存持久数据.如果有更简单的方法,请告诉我.

Rom*_*eau 13

你可以

  1. 序列化数组或包含数组的类.
  2. 以格式化方式将数组写为两行,例如JSON,XML或CSV.

这是第一个代码(你可以用数组替换Queue) Serialize

public static void main(String args[]) {
  String[][] theData = new String[2][1];

  theData[0][0] = ("r0 c1");
  theData[1][0] = ("r1 c1");
  System.out.println(theData.toString());

  // serialize the Queue
  System.out.println("serializing theData");
  try {
      FileOutputStream fout = new FileOutputStream("thedata.dat");
      ObjectOutputStream oos = new ObjectOutputStream(fout);
      oos.writeObject(theData);
      oos.close();
      }
   catch (Exception e) { e.printStackTrace(); }
}
Run Code Online (Sandbox Code Playgroud)

反序列化

public static void main(String args[]) {
   String[][] theData;

   // unserialize the Queue
   System.out.println("unserializing theQueue");
   try {
    FileInputStream fin = new FileInputStream("thedata.dat");
    ObjectInputStream ois = new ObjectInputStream(fin);
    theData = (Queue) ois.readObject();
    ois.close();
    }
   catch (Exception e) { e.printStackTrace(); }

   System.out.println(theData.toString());     
}
Run Code Online (Sandbox Code Playgroud)

第二个更复杂,但具有人类和其他语言可读的好处.

读写为XML

import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;

public class XMLSerializer {
    public static void write(String[][] f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static String[][] read(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        String[][] o = (String[][])decoder.readObject();
        decoder.close();
        return o;
    }
}
Run Code Online (Sandbox Code Playgroud)

往返于JSON

谷歌有一个很好的库可以在http://code.google.com/p/google-gson/上转换为JSON, 你可以简单地将你的对象写入JSOn,然后将其写入文件.阅读做相反的事情.