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

查看:63
本文介绍了为什么我的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 不可变 concat()将返回一个新的 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天全站免登陆