简体   繁体   English

InputStream Java

[英]Inputstream java

Since I am new to Java, I need some help about some basic things on Java. 由于我是Java新手,因此需要有关Java基本知识的一些帮助。 I have two questions. 我有两个问题。 They may be very simple(they are at least in C++), but I couldn't figure out how to do it in Java. 它们可能非常简单(至少在C ++中是这样),但是我不知道如何在Java中做到这一点。

(i) How to split line with comma separated values into separate strings? (i)如何用逗号分隔的值将行分割为单独的字符串?

Suppose I have an input(text) file like: 假设我有一个输入(文本)文件,例如:

 zoo,name,cszoo,address,miami  

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

I want to read the input line by line from file and get the strings between commas for each line 我想从文件中逐行读取输入,并获取每行逗号之间的字符串

(ii) Calling sub class constructor (ii)调用子类构造函数

If I have a superclass called Animal and a subclasses called Dog and Cat. 如果我有一个叫做Animal的超类和一个叫做Dog and Cat的子类。 While I read them from input, I put them into a Vector as an Animal. 当我从输入中读取它们时,我将它们放入动物矢量中。 But I need to call their constructor as if they are Dog or Cat. 但是我需要称呼它们的构造函数就像它们是Dog或Cat。 How do I do it in Java 我该如何用Java做

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))
}

Use a BufferedReader in combination with a FileReader to read from files. 结合使用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(",");
}

The idea is that a buffered reader is used to wrap around basic readers. 这个想法是使用缓冲的读取器来包装基本读取器。 A buffered reader uses a buffer which speeds up things. 缓冲的读取器使用缓冲区来加快处理速度。 The buffered reader doesn't actually read the file. 缓冲的读取器实际上并不读取文件。 It is the underlying FileReader that reads it, but the buffered reader does this "behind the scenes". 底层的FileReader读取它,但是缓冲的读取器在“幕后”执行此操作。

Another, more frequently seen code snippet is this, but it might be more difficult to understand: 另一个更常见的代码段是这个,但可能更难理解:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM