简体   繁体   中英

Inputstream java

Since I am new to Java, I need some help about some basic things on 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.

(i) How to split line with comma separated values into separate strings?

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

If I have a superclass called Animal and a subclasses called 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. How do I do it in 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 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".

Another, more frequently seen code snippet is this, but it might be more difficult to understand:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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