java 在文件中保存对象会产生错误:“FileOutputStream 无法解析为类型”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7979899/
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 22:32:41  来源:igfitidea点击:

Saving objects in files produces error: "FileOutputStream cannot be resolved to a type"

javafileserializationobject

提问by vedran

I'm trying to save an object, I googled the HowTo and got a tutorial on this issue. However since I never worked before with this I'm experiencing problems I can't resolve.

我正在尝试保存一个对象,我在 Google 上搜索了 HowTo 并获得了有关此问题的教程。但是,由于我以前从未使用过此方法,因此遇到了无法解决的问题。

So I have a huge class Course(contains all sort of things, variables, collectors...) which I'm trying to save in a file.

所以我有一个很大的类Course(包含各种东西、变量、收集器......),我试图将它保存在一个文件中。

import java.io.Serializable;
class Person implements Serializable {
... }

Now, I send an object to a class Save.java and try to save it :

现在,我将一个对象发送到一个类 Save.java 并尝试保存它:

class Save {

    protected void saveCourse (Course course) {

        FileOutputStream courseFile = new FileOutputStream("course.data");

        ObjectOutputStream courseObj = new ObjectOutputStream(courseFile);

        courseObj.writeObject(course);
    }
}

When I try to compile it FileOutputStream and ObjectOutputStream "cannot be resolved to a type". Aren't they suppose to be predefined. How can I fix this

当我尝试编译 FileOutputStream 和 ObjectOutputStream 时,“无法解析为类型”。他们不应该是预定义的。我怎样才能解决这个问题

Tutorial where I got this can be found here.

我得到这个的教程可以在这里找到。

回答by Joachim Sauer

You need to import FileOutputStreamand ObjectOutputStream.

您需要导入FileOutputStreamObjectOutputStream.

Since they are both in the java.iopackage, that means that you'll need to add this to the top of your file (under the packagedeclaration, if you have one):

由于它们都在java.io包中,这意味着您需要将其添加到文件的顶部(在package声明下,如果您有的话):

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

Also be careful about choosing your Java tutorials: there are lotsof badtutorials out there. The official Java tutorials from Oracleare pretty good (at least they are muchbetter than most other stuff out there) and should cover everything you need for quite some time.

另外要小心选择你的Java教程:有很多不好的教程在那里。Oracle官方 Java 教程非常好(至少它们比那里的大多数其他东西好得多)并且应该涵盖您在相当长一段时间内需要的所有内容。

For example there's a nice tutorial about using ObjectOutputStreamand related classes.

例如,有一个关于使用ObjectOutputStream和相关类很好的教程

More details about packages and importing can be found in this tutorial.

可以在本教程中找到有关包和导入的更多详细信息。

回答by George Otieno

To handle exceptions, normally put your code in a try-catch block

要处理异常,通常将您的代码放在 try-catch 块中