2012-03-03 62 views
0

由於我不熟悉Java,因此我需要一些有關Java的基本知識的幫助。 我有兩個問題。它們可能非常簡單(至少在C++中),但我無法弄清楚如何在Java中完成它。Inputstream java

(i)如何將逗號分隔的行拆分爲單獨的字符串?

假設我有一個輸入(文本)文件,如:

zoo,name,cszoo,address,miami 

    ...,...,...,.... 

我想讀通過文件線路輸入線,並得到逗號之間的字符串的每一行

(II)調用子類的構造函數

如果我有一個名爲Animal的超類和一個名爲Dog and Cat的子類。當我從輸入中讀取它們時,我將它們作爲一個動物放入Vector中。但我需要調用它們的構造函數,就好像它們是Dog或Cat。如何在Java中執行此操作

+0

你嘗試過什麼,和它不工作是什麼?顯示迄今爲止嘗試的代碼。 – 2012-03-03 23:43:29

+0

我不能做任何事情inputsream實際上 – user1133409 2012-03-03 23:44:20

+0

不要忘了這個標籤作爲作業 – Kevin 2012-03-03 23:46:23

回答

1
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
// or, to read from a file, do: 
// BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
String line; 
while ((line = br.readLine()) != null) { 
    String[] a = line.split(","); 

    // do whatever you want here 
    // assuming the first element in your array is the class name, you can do this: 
    Animal animal = Class.forName(a[0]).newInstance(); 

    // the problem is that that calls the zero arg constructor. But I'll 
    // leave it up to you to figure out how to find the two arg matching 
    // constructor and call that instead (hint: Class.getConstructor(Class[] argTypes)) 
} 
+0

我應該如何實現的漁獲物和嘗試的一部分?還什麼我不明白這裏的是,例如(動物園,12,拉拉).zoo是我的班級名稱,拉拉和12是屬性。我將如何定義它在任何你想在這裏部分 – user1133409 2012-03-03 23:51:31

+0

放在整個事情的try/catch。我認爲你會看到唯一的例外是找不到文件,而且無論如何也沒什麼可以做的。 – Kevin 2012-03-03 23:55:15

+0

你可以使用反射來實例化你的對象。並依靠構造函數提供與您的輸入參數相匹配的重載。 – Kevin 2012-03-03 23:57:00

0

將BufferedReader與FileReader結合使用以從文件讀取數據。

BufferedReader reader = new BufferedReader(new FileReader("yourfile.txt")); 

for (String line = reader.readLine(); line != null; line = reader.readLine()) 
{ 
    // handle your line here: 
    // split the line on comma, the split method returns an array of strings 
    String[] parts = line.split(","); 
} 

這個想法是,使用緩衝讀取器來環繞基本讀取器。緩衝讀取器使用緩衝器來加快速度。緩衝讀取器實際上不讀取文件。它是讀取它的基礎FileReader,但是緩衝讀取器在「幕後」執行此操作。

另一個更經常看到的代碼片段是這樣的,但它可能是比較難理解:

String line = null; 
while ((line = reader.readLine()) != null) 
{ 

} 
+0

我應該如何實現的漁獲物和嘗試的一部分?還有什麼我不明白在這裏的是,例如(動物園,12,拉拉).zoo是我的課程名稱,lala和12是屬性。我將如何將它定義在你想要的任何地方 – user1133409 2012-03-03 23:55:09