【问题标题】:Java - Reading Objects from a text fileJava - 从文本文件中读取对象
【发布时间】:2012-11-16 16:38:02
【问题描述】:

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

i) 形状 ii) 广场 iii) 矩形 iv) 圈子 v) 三角形 vi) 画布 vii) 申请

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

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

这是代码:

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

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

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

【问题讨论】:

  • 错误是哪一行引起的?
  • 是由这一行引起的:Shapes.add((Shape)temp.get(i));
  • 是 ArrayList 的形状吗??
  • 是的。 Shapes 是 Shape 类型的数组列表

标签: java file text io


【解决方案1】:

您需要编写一个读取器来获取输入字符串,并从中生成一个形状。这是一个简单的示例,使用Java Date class 向您展示这是如何工作的。没有您的 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);

【讨论】:

  • 形状的构造函数是 Shape(int x, int y)
  • 我刚刚有了一个想法。我只会将形状的类型和坐标保存在文本文件中,然后使用它们重新创建形状。谢谢你的回答:)
【解决方案2】:

您正在向 ArrayList 添加一个字符串。

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

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

在这里你试图cast一个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));

【讨论】:

    【解决方案3】:

    您应该使用ObjectOutputStream 来编写形状列表,然后从ObjectInputStream 中提取它们:

    out.writeObject(Shapes);
    
    Shapes = (ArrayList)in.readObject();
    

    假设ShapesArrayList

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多