因为我是Java新手,所以我需要一些关于Java的基本知识的帮助。我有两个问题。它们可能非常简单(至少在C++中),但我不知道如何在Java语言中实现它。
(i)如何将逗号分隔值的行拆分成单独的字符串?
假设我有一个输入(文本)文件,如下所示:
zoo,name,cszoo,address,miami
...,...,...,....我想从文件中逐行读取输入,并为每一行获取逗号之间的字符串
(ii)调用子类构造函数
如果我有一个名为Animal的超类和一个名为Dog和Cat的子类。当我从输入中读取它们时,我将它们放入一个Vector as a Animal。但我需要像调用Dog或Cat一样调用它们的构造函数。如何在Java中完成此操作
发布于 2012-03-04 07:43:48
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))
}发布于 2012-03-04 07:44:36
结合使用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)
{
}https://stackoverflow.com/questions/9550829
复制相似问题