在java中是否有RandomAccessFile的readObject()替代方案

发布于 2024-12-17 18:17:46 字数 497 浏览 0 评论 0原文

我正在尝试保存几个字符串,但我目前正在使用 ObjectInputStream,它显然不会以永久方式保存我的数据。这是我在项目中评论的代码。它以临时方式保存字符串。每当我退出程序时,数据就会消失:

ObjectInputStream FileIn= new ObjectInputStream(new FileInputStream("cars.txt"));

//AND HERE IS THE CODE FOR THE RandomAccessFile VERSION:
RandomAccessFile FileIn = new RandomAccessFile("cars.txt", "rw");

  au=(Cars)FileIn.readObject(); //THIS readObject(), is giving me errors
  //Cars is a Class

是否有其他替代方法可以用来读取 RandomAccessFile...请帮助并表示感谢。

I'm trying to save a couple of Strings but I'm currently using ObjectInputStream, which apparently doesn't save my data in a permanent manner. Here is the code which I commented in my project. It saves the string in a temporal manner. Anytime I exit my program, puff the data is gone:

ObjectInputStream FileIn= new ObjectInputStream(new FileInputStream("cars.txt"));

//AND HERE IS THE CODE FOR THE RandomAccessFile VERSION:
RandomAccessFile FileIn = new RandomAccessFile("cars.txt", "rw");

  au=(Cars)FileIn.readObject(); //THIS readObject(), is giving me errors
  //Cars is a Class

Is there any other alternative that I can use to read RandomAccessFile... Please help and thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

傲影 2024-12-24 18:17:46

就像 FileInputStream 一样,您需要将 RandomAccessFile 包装在 ObjectInputStream 中。即 RandomAccessFile 不会给你买任何东西。

final RandomAccessFile raf = new RandomAccessFile("file.dat", "r");
ObjectInputStream ois = new ObjectInputStream(new InputStream() {
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return raf.read(b, off, len);
    }

    @Override
    public int read() throws IOException {
        return raf.read();
    }
});

Just like FileInputStream, you need to wrap a RandomAccessFile in an ObjectInputStream. i.e. RandomAccessFile doesn't buy you anything.

final RandomAccessFile raf = new RandomAccessFile("file.dat", "r");
ObjectInputStream ois = new ObjectInputStream(new InputStream() {
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return raf.read(b, off, len);
    }

    @Override
    public int read() throws IOException {
        return raf.read();
    }
});
自此以后,行同陌路 2024-12-24 18:17:46

对于简单的 String 对象,使用普通的 DataInputStream / DataOutputStream 会容易得多:

package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class TestFile {

    static final String FILE = "/tmp/cars.txt";

    public static void main(String[] args) {
    try {
        List<String> strs = new ArrayList<String>();
        strs.add("Audi");
        strs.add("Seat");
        strs.add("Renault");

        saveStrings(strs);

        strs = loadStrings();

        System.out.println("Read strings: " + strs);

    } catch (Exception e) {

    }
    }

    static List<String> loadStrings() throws Exception {
    DataInputStream dis = null;
    List<String> list = new ArrayList<String>();
    try {
        dis = new DataInputStream(new FileInputStream(FILE));
        while (dis.available() > 0) {
        list.add(dis.readUTF());
        }
    } finally {
        if (dis != null)
        dis.close();
    }

    return list;
    }

    static void saveStrings(List<String> list) throws Exception {
    DataOutputStream dos = null;

    try {
        dos = new DataOutputStream(new FileOutputStream(FILE));
        for (String str : list) {
        dos.writeUTF(str);
        }
    } finally {
        if (dos != null)
        dos.close();
    }
    }

}

For simple String objects is far easier using plain DataInputStream / DataOutputStream:

package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class TestFile {

    static final String FILE = "/tmp/cars.txt";

    public static void main(String[] args) {
    try {
        List<String> strs = new ArrayList<String>();
        strs.add("Audi");
        strs.add("Seat");
        strs.add("Renault");

        saveStrings(strs);

        strs = loadStrings();

        System.out.println("Read strings: " + strs);

    } catch (Exception e) {

    }
    }

    static List<String> loadStrings() throws Exception {
    DataInputStream dis = null;
    List<String> list = new ArrayList<String>();
    try {
        dis = new DataInputStream(new FileInputStream(FILE));
        while (dis.available() > 0) {
        list.add(dis.readUTF());
        }
    } finally {
        if (dis != null)
        dis.close();
    }

    return list;
    }

    static void saveStrings(List<String> list) throws Exception {
    DataOutputStream dos = null;

    try {
        dos = new DataOutputStream(new FileOutputStream(FILE));
        for (String str : list) {
        dos.writeUTF(str);
        }
    } finally {
        if (dos != null)
        dos.close();
    }
    }

}
千仐 2024-12-24 18:17:46

如果您询问是否可以使用 RandomAccessFile 在对象流内部查找并读取对象,那么简短的答案是“否”。序列化对象流使用指向先前使用的对象的向后指针进行大量编码,包括先前转储的类定义等。

我们有类似的要求,并编写了一些代码,这些代码偶尔关闭并重新打开序列化流,并记录这些断点的位置。这并没有使我们能够读取特定的对象,但它确实使我们能够附加到序列化流并跳过文件的特定部分 - 跳到下一个中​​断。

If you are asking whether you can use RandomAccessFile to seek around inside an object stream and read objects then the short answer is "no". Serialized object streams are heavily encoded with backwards pointers to previously used objects including previously dumped class definitions, etc..

We had a similar requirement and wrote some code which closes and re-opens the serialized stream once and a while and recorded the positions of these break points. This didn't give us the ability to read a particular object but it did give us the ability to append to serialized stream and to skip over a particular portion of the file -- skip to the next break.

孤君无依 2024-12-24 18:17:46

那么你必须调用,writeObject()而不是readObject(),它实际上是从磁盘读取到内存,当然,当程序结束时,内存也会结束被该程序使用。

Well you have to invoke, writeObject() instead of readObject() which is actually to read from disk to memory, and of course when the program ends, so does the memory used by that program.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文