·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » java io读取文件到String

java io读取文件到String

类别: JAVA教程  评论数:0 总得分:0
  public static String loadAFileToStringDE1(File f) throws IOException { 
        long beginTime = System.currentTimeMillis();
        InputStream is = null;
        String ret = null;
        try {
            is = new BufferedInputStream( new FileInputStream(f) );
            long contentLength = f.length();
            ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) > 0) {
                outstream.write(buffer, 0, len);
            }           
            outstream.close();
            ret = outstream.toString();
            //byte[] ba = outstream.toByteArray();
            //ret = new String(ba);
        } finally {
            if(is!=null) {try{is.close();} catch(Exception e){} }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(\"方法1用时\"+ (endTime-beginTime) + \"ms\");
        return ret;       
    }
   

    public static String loadAFileToStringDE2(File f) throws IOException { 
        long beginTime = System.currentTimeMillis();
        InputStream is = null;
        String ret = null;
        try {
            is =  new FileInputStream(f) ;
            long contentLength = f.length();
            byte[] ba = new byte[(int)contentLength];
            is.read(ba);
            ret = new String(ba);
        } finally {
            if(is!=null) {try{is.close();} catch(Exception e){} }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(\"方法2用时\"+ (endTime-beginTime) + \"ms\");
        return ret;       
    }   
   

 

    public static String loadAFileToStringDE3(File f) throws IOException {
        long beginTime = System.currentTimeMillis();
        BufferedReader br = null;
        String ret = null;
        try {
            br =  new BufferedReader(new FileReader(f));
            String line = null;
            StringBuffer sb = new StringBuffer((int)f.length());
            while( (line = br.readLine() ) != null ) {
                sb.append(line).append(LINE_BREAK);
            }
            ret = sb.toString();
        } finally {
            if(br!=null) {try{br.close();} catch(Exception e){} }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(\"方法3用时\"+ (endTime-beginTime) + \"ms\");
        return ret;       
    }

3个方法去读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S





-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1