Write Java objects to file

白昼怎懂夜的黑 提交于 2019-12-04 09:59:07

问题


Is it possible to write objects in Java to a binary file? The objects I want to write would be 2 arrays of String objects. The reason I want to do this is to save persistent data. If there is some easier way to do this let me know.


回答1:


If you want to write arrays of String, you may be better off with a text file. The advantage of using a text file is that it can be easily viewed, edited and is usuable by many other tools in your system which mean you don't have to have to write these tools yourself.

You can also find that a simple text format will be faster and more compact than using XML or JSON. Note: Those formats are more useful for complex data structures.

public static void writeArray(PrintStream ps, String... strings) {
    for (String string : strings) {
        assert !string.contains("\n") && string.length()>0;
        ps.println(strings);
    }
    ps.println();
}

public static String[] readArray(BufferedReader br) throws IOException {
    List<String> strings = new ArrayList<String>();
    String string;
    while((string = br.readLine()) != null) {
        if (string.length() == 0)
            break;
        strings.add(string);
    }
    return strings.toArray(new String[strings.size()]);
}

If your start with

String[][] theData = { { "a0 r0", "a0 r1", "a0 r2" } {"r1 c1"} }; 

This could result in

a0 r0
a0 r1
a0 r2

r1 c1

As you can see this is easy to edit/view.

This makes some assumptions about what a string can contain (see the asset). If these assumptions are not valid, there are way of working around this.




回答2:


You could

  1. Serialize the Arrays, or a class that contains the arrays.
  2. Write the arrays as two lines in a formatted way, such as JSON,XML or CSV.

Here is some code for the first one (You could replace the Queue with an array) 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(); }
}

Deserialize

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());     
}

The second one is more complicated, but has the benefit of being human as well as readable by other languages.

Read and Write as 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;
    }
}

To and From JSON

Google has a good library to convert to and from JSON at http://code.google.com/p/google-gson/ You could simply write your object to JSOn and then write it to file. To read do the opposite.




回答3:


You can do it using Java's serialization mechanism, but beware that serialization is not a good solution for long-term persistent storage of objects. The reason for this is that serialized objects are very tightly coupled to your Java code: if you change your program, then the serialized data files become unreadable, because they are not compatible anymore with your Java code. Serialization is good for temporary storage (for example for an on-disk cache) or for transferring objects over a network.

For long-term storage, you should use a standard and well-documented format (for example XML, JSON or something else) that is not tightly coupled to your Java code.

If, for some reason, you absolutely want to use a binary format, then there are several options available, for example Google protocol buffers or Hessian.




回答4:


One possibility besides serialization is to write Objects to XML files to make them more human-readable. The XStream API is capable of this and uses an approach that is similar to serialization.

http://x-stream.github.io/




回答5:


You need to write object, not class, right? Because classes are already compiled to binary .class files.

Try ObjectOutputStream, there's an example
http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html



来源:https://stackoverflow.com/questions/3030642/write-java-objects-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!