1

我有一个带有几个类的 Java 程序,它们是:

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

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

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

这是代码:

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

实际上,应用程序给了我java.lang.String 无法转换为 shape_assignment.Shape的错误。

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

4

3 回答 3

2

您需要编写一个读取器来获取输入字符串,并从中制作一个形状。这是一个简单的示例,向您展示如何使用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);
于 2012-11-16T16:44:30.080 回答
0

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

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

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

在这里,您尝试将String ( temp.get(i) 将返回 String) 转换为Shape type,这会导致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));
于 2012-11-16T16:48:35.127 回答
0

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

out.writeObject(Shapes);

Shapes = (ArrayList)in.readObject();

假设Shapes是一个ArrayList.

于 2012-11-16T17:02:32.557 回答