作者lovdkkkk (dk)
看板java
标题Re: [问题] 合成长字串时出现OutOfMemoryError
时间Sun Jul 3 10:39:44 2011
※ 引述《ntb (錩哥超口爱)》之铭言:
: 我的程式目的是想将文字档变成一行字串 (StringBuffer的物件)
: 每个档案的大小约40 mb,
: 因为第一行的标题不想串入StringBuffer的物件内,
: 所以想跳掉第一行,
: 但不知道为什麽少串这行,在执行时反而会发生错误。
: (若拿掉String str = input.readLine()就可以)
: import java.io.*;
: public class Test{
: public static void main(String[] args) throws Exception {
: String file = args[0];
: BufferedReader input0 =
: new BufferedReader(new FileReader(new File(file)));
: //放欲开启档案的档名 第一行1.txt 第二行2.txt...
: String str0;
: while ((str0= input0.readLine()) != null){
: BufferedReader input =
: new BufferedReader(new FileReader(new File(str0)));
: String str = input.readLine();
: 原本想利用这行来跳过标题列
: 但多这一行就会有错误 OutOfMemoryError: Java heap space
: StringBuffer sb = new StringBuffer();
: while ((str = input.readLine()) != null){
: sb = sb.append(str);
: 问题显示是出现在这
: }
: System.out.println(sb.length());
: input.close();
: }
: input0.close();
: }
: }
: 请板上有经验的板友前辈不吝赐教
: 非常感谢
一次读一个字元自己 handle 的版本,
这里是用来跳过超长的第一行用的 (假设是第一行超长)
自己测试 while 回圈中是保持只使用 不到 5mb,
也可拿来自己 handle 要 append 的内容,
只读固定长度再自己看要怎麽加
测试用的档案在
http://www.badongo.com/file/25548783
也可以自己开一个 .txt 档,
罚写 a very long line that hits 40 mega bytes 到一行有 40mb,
再换行打点别的来测
try{
File srcFile = new File( "test.txt" );
BufferedReader br =
new BufferedReader(new InputStreamReader(
new FileInputStream(srcFile), "UTF-8"));
char ch = (char)br.read();
while( ch != '\n' ) {
ch = (char)br.read();
//System.out.println(ch);
//Runtime rt = Runtime.getRuntime();
//long memMb = (rt.totalMemory()-rt.freeMemory())/1024/1024;
//System.out.println("total memory is "+ memMb + " MB");
}
System.out.println("first line passed");
System.out.println(br.readLine());
}
catch(Exception e){
e.printStackTrace();
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.224.41.43
1F:推 ntb:非常感谢lovdkkkk大,真的获益良多 07/03 17:50
2F:推 ntb:虽然目的不只是为了跳过第一行,而是要截特定为范围的字串 07/03 17:53