编写Java对象文件 [英] Write Java objects to file

查看:149
本文介绍了编写Java对象文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以用Java编写的对象为二进制文件?我想写的对象将是字符串对象的2个数组。我想这样做的原因是为了保存持久性数据。如果有一些更简单的方法来做到这一点让我知道。

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.

在此先感谢!

推荐答案

如果你想写的String数组,你可能是一个文本文件更好。使用文本文件的好处是,它可以很容易地查看,编辑和是在你的系统,它意味着你不必有自己写这些工具的许多其他工具usuable。

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.

您还可以找到一个简单的文本格式比使用XML或JSON更快,更紧凑。注意:这些格式是复杂的数据结构更为有用。

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

如果你的启动与

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

这可能会导致

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.

这篇关于编写Java对象文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆