2012-11-16 68 views
1

我在Java程序的一些類,它們是:爪哇 - 從文本文件中讀取對象

我)形狀 II)廣場 III)矩形 IV)圈 V)三角 VI)繪圖畫布 七)申請

正方形,長方形,圓形和三角形所有從類外形繼承現在

,在繪圖畫布類,我有兩種方法,一種用於將Shape類型的對象寫入文件,另一種用於從文件中讀取對象。

這是代碼:

保存到文件的方法完美地工作。但是,從文件中讀取對象並將它們附加到Shapes ArrayList中時遇到問題。

事實上,應用程序給我的錯誤是,java.lang.String不能轉換爲shapes_assignment.Shape

如何讀取存儲在文本文件中的文本並使用它重新創建對象?謝謝:)

+0

什麼行是由錯誤造成的? –

+0

它是由以下行引起的: Shapes.add((Shape)temp.get(i)); – Matthew

+0

是形狀ArrayList ?? – PermGenError

回答

2

你需要寫一個讀取器,將採取輸入字符串,並從中做出一個形狀。下面是一個簡單的示例,使用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); 
+0

形狀的構造函數是Shape(int x,int y) – Matthew

+0

我剛剛有一個想法。我將只保存文本文件中的形狀和座標的類型,然後使用它們重新創建形狀。謝謝您的回答 :) – Matthew

0

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

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

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

在這裏你試圖一個字符串(temp.get(I)將一個字符串返回)形狀類型,這是導致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)); 
0

您應該使用ObjectOutputStream寫形狀列表,並從ObjectInputStream retreave他們:

out.writeObject(Shapes); 

Shapes = (ArrayList)in.readObject(); 

假設ShapesArrayList