0

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

1
  • Umm, well you are using System.out.println NOT System.out.print Commented Mar 27, 2013 at 20:58

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow and I didn't even realize, I knew it would have been something obvious -.-
0

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.

Comments

0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.