字符串拼接效率比较

来源:互联网 发布:mac虚拟机共享网络 编辑:程序博客网 时间:2024/05/04 00:29

一、遇到问题

/****读取文件***/    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.csdn.net/rmn190/article/details/1492013

0 0