2012-03-03 69 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