Java:对象输入流

发布于 2024-12-04 06:20:18 字数 367 浏览 0 评论 0原文

    public void bar(String fileName) throws IOException{
    FileInputStream fileIn = new FileInputStream(fileName);
    ObjectInputStream in = new ObjectInputStream(fileIn);
    Map map = (HashMap) in.readObject();
}

我试图理解这段代码的作用。

我们创建一个流,这样我们就可以读取该文件。这个ObjectInputStream有什么作用?我们是否读取对象并用它制作地图?我显然不明白,我会很高兴得到你的帮助。

    public void bar(String fileName) throws IOException{
    FileInputStream fileIn = new FileInputStream(fileName);
    ObjectInputStream in = new ObjectInputStream(fileIn);
    Map map = (HashMap) in.readObject();
}

I'm trying to understand what this piece of code does.

We create a stream, so we'll be able to read from this file. What does this ObjectInputStream do? Do we read object and make a map out of it? I clearly don't understand, and I'll be glad for your help.

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

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

发布评论

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

评论(2

末が日狂欢 2024-12-11 06:20:18

ObjectInputStream 将读取由 ObjectOutputStream 在文件中序列化的对象,

public void bar(String fileName) throws IOException{
    FileInputStream fileIn = new FileInputStream(fileName); //1
    ObjectInputStream in = new ObjectInputStream(fileIn); //2
    Map map = (HashMap) in.readObject(); //3
}

此代码将从

  1. fileName 创建 InputStream(字符串,文件的绝对路径)
  2. 创建 ObjectInputStream,以读取保存在该文件中的对象
  3. 将创建 HashMap 对象,保存到 Map map 变量中

这意味着,在文件中,有一个 HashMap 类型的对象它将被投射到使用此代码的 Map

ObjectInputStream will read Object serialized in file by ObjectOutputStream

public void bar(String fileName) throws IOException{
    FileInputStream fileIn = new FileInputStream(fileName); //1
    ObjectInputStream in = new ObjectInputStream(fileIn); //2
    Map map = (HashMap) in.readObject(); //3
}

this code will

  1. create InputStream from fileName (String, absolute path to file)
  2. create ObjectInputStream, to read objects saved in that file
  3. will create HashMap object, saved to Map map variable

So that mean, in file, there is a object of type HashMap which will be casted to Map with this code

拥抱影子 2024-12-11 06:20:18

我的猜测是它正在读取之前使用相应的 Out/Write 方法写入文件的 HashMap

My guess is it is reading a HashMap that was previously written to the file using corresponding Out/Write methods.

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