我得到一個538MB的ASCII文件,16807行,每行有16807個0和1個空格分隔。我想要將所有這些值存儲在列表中,以便將每一行存儲在新列表中。讀取和存儲大型ASCII文件的內容
在之前的項目中,我爲文本文件做了下面的代碼,但是使用ASCII文件,它會引發Java堆空間錯誤。
ArrayList<ArrayList<String>> listOflists = new ArrayList<ArrayList<String>>();
FileInputStream fstream = new FileInputStream("C:\Users...\file.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while (true)
{
String line = br.readLine();
if (line == null) {
break;
}
Scanner tokenize = new Scanner(line);
ArrayList<String> tokens = new ArrayList<String>();
while (tokenize.hasNext())
{
tokens.add(tokenize.next());
}
listOflists.add(tokens);
}
br.close();
現在我做了這段代碼,但又一次拋出Java堆空間錯誤。
String inputFile = "C:\Users...\file.txt";
LinkedList<LinkedList<Character>> charList = new LinkedList<LinkedList<Character>>();
File file = new File(inputFile);
Reader reader = new FileReader(file);
char val = 0;
int c;
int iLine = 0;
while((c = reader.read()) != -1) {
val = (char)c;
charList.add(new LinkedList<Character>());
if((c == 48) || (c == 49)){ //ascii code for 0 is 48 and for 1 is 49
charList.get(iLine).add(val);
}
if(c == 92){ //ascii code for "/" is 92 as to know when it changes line
iLine++;
}
}
reader.close();
任何想法?
增加堆內存,或以較少的內存消耗的方式存儲它。 – Kayaman
我用這個-Xmx1024m增加堆內存,但是錯誤依然存在,問題的目的是找到一種更少的內存消耗方式,因爲我找不到任何東西。 – lostromos
這樣做有什麼意義?讀取文件並將其存儲在一個位域中,這會大大減少內存使用量 – Marged