So I'm following this Android app dev course on Udacity and I'm confused. The following function returns a JSON, but I don't understand the usage of the delimiter ("\A").
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
So what the \A delimiter does? How does it work?
In Java, delimiters are the characters that split (separate) the string into tokens. Java allows us to define any characters as a delimiter.
A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
The useDelimiter(String pattern) method of java. util. Scanner class Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
The useDelimiter(String pattern)
method takes a regex pattern as parameter.
Regex patterns are documented in the javadoc of the Pattern
class.
The \A
pattern is listed in the Boundary matchers block:
\A
- The beginning of the input
This basically specifies that there is no delimiter, so the next()
method will read the entire input stream.
The question code is equivalent to the following code using the Apache Commons IO library:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
String content = IOUtils.toString(urlConnection.getInputStream(), Charset.defaultCharset());
return (content.isEmpty() ? null : content);
} finally {
urlConnection.disconnect();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With