I have code which consumes an InputStream
through a Scanner
which looks like
String input = scanner.nextLine().toLowerCase();
if (input.isEmpty()) {
return defaultAnswer;
} else if (input.startsWith("y")) {
return true;
} else if (input.startsWith("n")) {
return false;
}
where the scanner is initialized by a given InputStream
coming from IOUtils.toInputStream("someString")
.
How would I be able to test the if (input.isEmpty())
path?
EDIT:
I swapped two lines in my code, and empty string (""
) results in a NoSuchElementException
, and a newline or carriage return results in an empty string being returned.
Either using IOUtils.toInputStream("")
or new ByteArrayInputStream(new byte[0])
may work.
The latter would certainly provide an empty stream, but it may make your code fail because there isn't an empty line to read - there's no line terminator. For example:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
InputStream stream = new ByteArrayInputStream(new byte[0]);
Scanner scanner = new Scanner(stream, "UTF-8");
String line = scanner.nextLine();
System.out.println(line);
}
}
That fails with:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Test.main(Test.java:10)
You can use Scanner.hasNextLine()
to check whether a call to nextLine()
is appropriate or not. You may want to do that in your code. It really depends on whether you're trying to model "input ended without a line" or "the user entered an empty line". Those are significantly different situations, and you should consider both of them.
If you want to provide a stream which contains a line break (i.e. "the user entered an empty line") then you might want to use IOUtils.toInputStream("\n")
instead. I'm nervous about the fact that that's not specifying a Charset
though - you should carefully consider what encoding you expect your input to be in.
See more on this question at Stackoverflow