Re: [問題] 合成長字串時出現OutOfMemoryError
※ 引述《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
推
07/03 17:50, , 1F
07/03 17:50, 1F
推
07/03 17:53, , 2F
07/03 17:53, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 4 篇):