2016-04-03 120 views
3

考慮讀取多個對象我有2個不同的類爪哇從文件

public class A { 

    String name; 
    int A1; 
    int A2; 

} 

,另一類是:

public class B { 

    String B0; 
    int B1; 
    int B2; 
} 

,現在我有一個包含一個整數的文件,並且幾個對象一個數B的和

的文件也能像

3 
"Jim"; 1;2 
"jef";3;5 
"Peter";6;7 
"aa";1;1 
"bb";2;3 
"cc";3;4 

可以認爲(在文件開頭)爲B類

的問題是,我怎麼能閱讀和獨立於A級,其餘對象是對象的數量文件中的所有對象?

主要問題是,我不知道如何從文件中讀取第一個int。我所做的是

 InputStream inputFileStream = Main.class.getResourceAsStream("/inputFile.txt"); 
ObjectInputStream ois = new ObjectInputStream(inputStream);  
int i = ois.readInt(); 
    ois.close(); 

,但它給我一個錯誤:

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 350A4261 
+0

你的問題是一個多步驟的問題,其步驟包括1)從文件中讀取行,2使用循環讀入第一個x A類型,然後一個while循環來讀取其餘行3)將每行轉換爲A或B類型。所以...... **你準確的**卡住了嗎?顯示你已經嘗試過的請。 –

+0

@HovercraftFullOfEels我已編輯我的問題 –

回答

0

The main problem is that i don't know how can i read the first int from the file.

您正在閱讀的文本文件,而不是一個數據文件,所以不要使用readInt()。要麼使用BufferedReader,要麼使用我的建議 - 掃描儀對象。

InputStream inputFileStream = Main.class.getResourceAsStream("/inputFile.txt"); 
Scanner scanner = new Scanner(inputFileStream); 
int int = scanner.nextInt(); // get that first int 
scanner.nextLine(); // go to the next line (swallow the end-of-line token) 
//..... 

然後使用相同的掃描器讀取線。使用

while (scanner.hasNextLine) { 
    String line = scanner.nextLine(); 
    // here process the line into an A or B depending on the results of a counter variable 
    // then increment the counter here 
} 

請注意,你的處理可能會使用字符串的方法split(...)分裂的;,創造一個String數組與你所需要的物品。然後你需要通過解析int相關的項目Integer.parseInt(...)

+0

但當我去的對象,我不得不改變我的streaminput。 對不對? –

+0

@KamyarParastesh:heck no。使用相同的掃描儀。見上面的編輯。你會想嘗試一下,看看會發生什麼。 –

+0

@KamyarParastesh:還有其他問題嗎? –