繁体   English   中英

Java - 从文本文件中读取对象

[英]Java - Reading Objects from a text file

我有一个包含多个类的 Java 程序,它们是:

i) 形状 ii) 方形 iii) 矩形 iv) 圆形 v) 三角形 vi) 绘图画布 vii) 应用

Square、Rectangle、Circle 和 Triangle 都继承自Shape

现在,在Drawing Canvas类中,我有两种方法,一种用于将 Shape 类型的对象写入文件,另一种用于从文件中读取对象。

这是代码:

保存到文件的方法工作得很好。 但是,我在从文件中读取对象并将它们附加到 Shapes ArrayList 时遇到问题。

事实上,应用程序给了我一个错误,即java.lang.String 无法转换为 shape_assignment.Shape

如何读取存储在文本文件中的文本并使用它再次重新创建对象? 谢谢 :)

您需要编写一个读取器来获取输入字符串,并从中生成一个形状。 下面是一个简单的示例,它使用Java Date 类向您展示这是如何工作的。 没有你的 Shape 构造函数,我无法为你编写你的 Shape 。

Date today=new Date();
long var_to_write=today.getTime();

//Save this in to a file, then read it out as long var_in_file

Date previousTime=new Date(var_in_file);

您正在将一个字符串添加到您的 ArrayList 中。

            while(input.hasNext())
            {
                temp.add(input.next());
            }

            Shapes.add((Shape)temp.get(i));

在这里您要一个String(temp.get(我)将返回一个字符串)形状类型,这是导致ClassCaseException。

从文件中读取并使用 Shape 实例填充 ArrayList (temp) 后创建一个 Shape 实例。

      List<Shape> temp = new ArrayList<Shape>();
      //read from the scanner and make an Shape object. 
       Shape shape = new Shape(your arguments to the Shape cons);
       now, while adding into shapes you wont need a case, as you made yourself sure that your ArrayList would only accept Shape

       shapes(temp.get(i));

您应该使用ObjectOutputStream来编写形状列表,并从ObjectInputStream检索它们:

out.writeObject(Shapes);

Shapes = (ArrayList)in.readObject();

假设Shapes是一个ArrayList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM