I have a file filled with all numbers with no spaces. I am trying to read this file in Java character by character into an integer array. I tried reading the file as an String then step through it char by char into an array but i think the file exceeded the String size limit.
As @Scary Wombat suggest, both of the max size of String and max size of array are Integer.MAX_VALUE
. We can refer to String max size , Array max size and List max size . Note, the specific max size should be Integer.MAX_VALUE
- 1 or -2 or -5 is irrelevant with this topic. For insurance purpose, we can use Integer.MAX_VALUE
- 6.
I suppose your number is very large and the amount of character in the file may exceed the maximum of Integer.MAX_VALUE
according to
I tried reading the file as an String then step through it char by char into an array but i think the file exceeded the String size limit.
To handle the maximum, I suggest you create another List
to hold the integer. The core concept of it is like dynamic array
but there are some differences. For dynamic array
, you are applying for another memory space and copy current elements into that space. You can refer to the code below:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
public class ReadFile {
public static void main(String args[]){
try{
File file = new File("number.txt");
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
ArrayList<ArrayList<Integer>> listContainer = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
int item;
while((item = reader.read()) != -1){
/*
* I assume you want to get the integer value of the char but not its ascii value
*/
list.add(item - 48);
/*
* Reach the maximum of ArrayList and we should create a new ArrayList instance to hold the integer
*/
if(list.size() == Integer.MAX_VALUE - 6){
listContainer.add(list);
list = new ArrayList<Integer>();
}
}
reader.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.