为什么我的Java字符串串联不起作用? [英] Why doesn't my Java string concatenation work?

查看:54
本文介绍了为什么我的Java字符串串联不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码运行时,它将获取网页的内容.

When this code runs, it gets the content of a webpage.

我想连接整个字符串,而不是将其打印到控制台,但是当我取消注释下面代码中的两行时, System.out.println(inputLine); 不打印任何内容(但是使用下面的行注释)和值 fileText = null

I wanted to concatenate that entire string rather than printing it to the console but when I uncomment the two lines in the code below, System.out.println(inputLine); prints nothing (but it worked with the line below commented) and the value fileText = null,

此错误来自何处?

import java.net.*;
import java.io.*;

public class URLReader {

    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String fileText = "";
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            //fileText.concat(inputLine);
            System.out.println(inputLine);
        in.close();
        //System.out.println(fileText);
    }
}

推荐答案

String 不可变

String is immutable and concat() will return a new String (check the linked doc), which you're not collecting.

您应该利用 StringBuilder 有效地构建字符串,然后完成操作后,调用 toString()以获得结果字符串.

You should make use of a StringBuilder to build a string efficiently, and then call toString() on that once you're complete to get he resultant String.

例如

StringBuilder sb = new StringBuilder();
while (....) {
   sb.append("more string data");
}
String str = sb.toString();

可以附加字符串,例如

   str = str + "more string data";

,但是由于实现了 String ,所以效率不是很高.构建 StringBuilder 以便有效执行串联.如果您知道要构建的 String 的大小,可以通过其初始容量调整 StringBuilder .

but it's not very efficient, due to the implementation of String. A StringBuilder is built in order to perform concatenation efficiently. You can tune a StringBuilder via its initial capacity if you have an idea of the size of String you're building.

您可能会看到一些资料来源引用了 StringBuffer .这非常相似,只不过它较旧并且默认情况下会同步其方法.在非线程环境中这很浪费,一般建议是首选 StringBuilder .

You may see some sources refer to a StringBuffer. That's very similar, except it's older and synchronises its methods by default. In a non-threaded environment that's wasteful and the general advice is to prefer StringBuilder.

这篇关于为什么我的Java字符串串联不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆