English 中文(简体)
Java InputStream != Readable
原标题:

I am using java.util.Scanner for things such as nextInt(), and all was working fine as long as I was using a java.lang.Readable (one and only constructor argument). However, when I changed to using an InputStream instead, Scanner.nextInt() never returns. Do you know why?

My implementation of the InputStream looks like this:

private static class ConsoleInputStream extends InputStream {
    ...
    private byte[] buffer;
    private int bufferIndex;
    public int read() throws IOException {
        ...
        while (...) {
            if (buffer != null && bufferIndex < buffer.length) {
                return buffer[bufferIndex++];    // THE COMMENT!
            }
            ...
        }
        ...
    }
}

When I print the data by THE COMMENT I (correctly) get stuff like 1 , 2 , for "12 ", etc. Is there some Scanner hookup, unbeknown to me, that cause this behavior?

最佳回答

From the javadocs for InputStream s read() method:

"Returns: the next byte of data, or -1 if the end of the stream is reached."

I would guess that you re never returning -1?

问题回答

I think the problem is with your self-built InputStream. Why did you build your own, rather than simply simply using System.in ?

Update:

Wanted input from a JTextField.

OK, got it. It usually doesn t make sense to use I/O handling to read stuff that s already available, in character form, but I can see how that would make your life easier with Scanner.

Still, you could probably have saved yourself some coding and grief by using a "finished" InputStream. What comes to mind is

InputStream is = new ByteArrayInputStream(myTextField.getText().getBytes());

Java I/O is yucky. Be glad the bright people from Sun have encapsulated most of it away for you.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签