将 Java 对象写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3030642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:01:20  来源:igfitidea点击:

Write Java objects to file

javafilebinarypersistent-storage

提问by Mark Szymanski

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

是否可以将 Java 中的对象写入二进制文件?我想写的String对象是 2 个对象数组。我想这样做的原因是为了保存持久数据。如果有更简单的方法可以让我知道。

采纳答案by Peter Lawrey

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.

您还可以发现,与使用 XML 或 JSON 相比,简单的文本格式会更快、更紧凑。注意:这些格式对于复杂的数据结构更有用。

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.

这对字符串可以包含的内容做出了一些假设(请参阅资产)。如果这些假设无效,则有办法解决此问题。

回答by Romain Hippeau

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.
  1. 序列化数组或包含数组的类。
  2. 以格式化的方式将数组写成两行,例如 JSON、XML 或 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

以 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

往返 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.

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

回答by James P.

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.

除了序列化之外的一种可能性是将对象写入 XML 文件以使其更易于人类阅读。XStream API 能够做到这一点,并使用类似于序列化的方法。

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

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

回答by Jesper

You can do it using Java's serializationmechanism, 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.

您可以使用 Java 的序列化机制来实现,但请注意,序列化对于对象的长期持久存储来说并不是一个好的解决方案。这样做的原因是序列化对象与您的 Java 代码非常紧密地耦合:如果您更改程序,那么序列化数据文件将变得不可读,因为它们不再与您的 Java 代码兼容。序列化适用于临时存储(例如磁盘缓存)或通过网络传输对象。

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.

对于长期存储,您应该使用与您的 Java 代码不紧密耦合的标准且有据可查的格式(例如 XML、JSON 或其他格式)。

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

如果出于某种原因,您绝对想使用二进制格式,那么有几个选项可用,例如Google protocol buffersHessian

回答by Nikita Rybak

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

你需要写对象,而不是类,对吧?因为类已经编译为二进制 .class 文件。

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

尝试 ObjectOutputStream,有一个例子
http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html