I am wanting to split a line up (inputLine) which is
Country: United Kingdom
City: London
so I'm using this code:
public void ReadURL() {
try {
URL url = new URL("http://api.hostip.info/get_html.php?ip=");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
String line = inputLine.replaceAll("\n", " ");
System.out.println(line);
}
in.close();
} catch ( Exception e ) {
System.err.println( e.getMessage() );
}
}
when you run the method the the output is still
Country: United Kingdom
City: London
not like it's ment to be:
Country: United Kingdom City: London
now i've tried using
\n,\\n,\r,\r\n
and
System.getProperty("line.separator")
but none of them work and using replace
, split
and replaceAll
but nothing works.
so how do I remove the newlines to make one line of a String?
more detail: I am wanting it so I have two separate strings
String Country = "Country: United Kingdom";
and
String City = "City: London";
that would be great
You should instead of using System.out.println(line);
use System.out.print(line);
.
The new line is caused by the println()
method which terminates the current line by writing the line separator string.
http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()
Read that. readLine method will not return any carriage returns or new lines in the text and will break input by newline. So your loop does take in your entire blob of text but it reads it line by line.
You are also getting extra newlines from calling println. It will print your line as read in, add a new line, then print your blank line + newline and then your end line + newline giving you exactly the same output as your input (minus a few spaces).
You should use print instead of println.
I would advise taking a look at Guava Splitter.MapSplitter
In your case:
// input = "Country: United Kingdom\nCity: London"
final Map<String, String> split = Splitter.on('\n')
.omitEmptyStrings().trimResults().withKeyValueSeparator(": ").split(input);
// ... (use split.get("Country") or split.get("City")
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.