字符串拼接效率比较

本文介绍了一种从文件中高效读取大量数据的方法。针对使用“+”操作逐行拼接字符串导致的大文件读取效率低下的问题,提供了一个改进方案:一次性将文件内容读入字节数组再转换为字符串,显著提升了处理速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、遇到问题

/****读取文件***/
    public String getFileText(String filePath){
        String retXMLStr = "";
        String read;
        filePath = filePath.replaceAll("\\\\", "/");
        File file = null;
        FileInputStream is =null;
            try {
                file = new File(filePath);
                is = new FileInputStream(file);
                if (!file.exists() || file.isDirectory()) {
                    return "";
                }
                /*
                //FileReader fileread = new FileReader(file);
                InputStreamReader fileread = new InputStreamReader(new FileInputStream(file));
                BufferedReader bufread = new BufferedReader(fileread);
                while ((read = bufread.readLine()) != null) {
                    // read = read+"/r/n";
                    retXMLStr = retXMLStr + read;
                }
                //这种写法效率太低了,1M的文件要一分钟,而且会将文件截断
                */

                byte[] bt = new byte[is.available()];
                is.read(bt);
                retXMLStr = new String(bt);
            } catch (Exception e) {
                retXMLStr = filePath;
                e.printStackTrace();
            }finally{
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        return retXMLStr;
    }

二、问题原因

如备注所说,用“+”的方式将一行一行读取来的文件流转为String,赋值给String变量,效率极其的低。当文件超过1M的时候,耗费时间60s左右,当文件较小的时候,并不明显。

三、参考资料
这里有篇比较字符串拼接的效率比较的文章,可以参考:
http://blog.youkuaiyun.com/rmn190/article/details/1492013

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值