2013-03-27 71 views
0

我想分割排队(inputLine),这是的Java:的replaceAll和.split换行不行

Country: United Kingdom 
City: London 

所以我用这个代码:

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()); 
    } 
} 

时你运行的方法的输出仍是

Country: United Kingdom 
City: London 

不喜欢它的彪是:

Country: United Kingdom City: London 

现在我已经使用

\n,\\n,\r,\r\n 

System.getProperty("line.separator") 

尝试,但他们没有工作,并且使用replacesplitreplaceAll但没有任何工程。

那么我该如何删除换行来创建一行字符串?

更详细:我想它,所以我有两个单独字符串

String Country = "Country: United Kingdom"; 

String City = "City: London"; 

这将是巨大

+0

嗯,还有你使用'System.out.println'不'System.out.print' – thatidiotguy 2013-03-27 20:58:56

回答

1

你应该的,而不是使用System.out.println(line);使用System.out.print(line);

新行是由println()方法造成的,该方法通过写入行分隔符字符串来终止当前行。

+0

哇我甚至没有意识到,我知道这将是明显的事情 - – 2013-03-27 21:05:08

0

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()

请阅读。 readLine方法不会返回任何回车符或文本中的新行,并会通过换行符来中断输入。所以你的循环会占用整个文本块,但它会逐行读取它。

您还可以通过调用println获得额外的换行符。它会将您的行打印为已读入,添加一个新行,然后打印空行+换行符,然后打印结束行+换行符,为您提供与输入完全相同的输出(减去几个空格)。

您应该使用print而不是println。

0

我将在番石榴Splitter.MapSplitter

劝考虑看看你的情况:

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