Java : replaceAll and . 分割换行符不起作用

标签 java string while-loop bufferedreader

我想分割一行(inputLine),它是

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

那就太好了

最佳答案

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

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

关于Java : replaceAll and . 分割换行符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669297/

相关文章:

java - JAX-WS,为什么收到的LinkedHashMap集合是空的?

python - 如何将字符串拆分为奇数序列?

regex - 正则表达式如何在幕后工作(在 CPU 级别)?

Python - 在字符串中查找单词

php - 限制 while 循环

Python:如何将while循环的值之和存储到一个变量中?

javascript - Node.js 文件系统 - 添加新文件时读取文件夹中的文件

java - UTF-8 编码字符串的字节数不符合预期

java - 将自定义铃声添加到 Ringtonemanager 以进行 Android 应用程序开发时出现问题吗?

java - JAX-WS 在客户端检索抛出的自定义异常