读取txt文本到一个字符串(java)

这篇博客详细解释了如何使用Java从txt文件高效读取内容到字符串数组。通过BufferedReader读取文件,当达到一定行数时停止。关键在于使用`list.toArray(new String[0])`,这利用了泛型方法`<T> T[] toArray(T[] a)`,创建一个指定类型的空数组作为模板,指导List转换为String数组。尽管创建了长度为0的数组,但这种方式避免了不必要的空间浪费,提高了效率。
摘要由CSDN通过智能技术生成

public static  String[] ReadFile(File file) throws IOException
 {
  BufferedReader br = null;
  List<String>list=new ArrayList<String>();
  FileReader fileReader=new FileReader(file);
  BufferedReader buf=new BufferedReader(fileReader);
  int i=0;
  String str=null;
  while((str=buf.readLine())!=null)
  {
   list.add(readLine);
   i++;
   if(i==2000000)//文件太大,读到2000000就被停止了
    break;
  }
  buf.close();
  return  list.toArray(new String[0]);
 }

 

 

 

为什么list.toArray(new String[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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值