簡體   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