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.
-
well if it exceeds the max String size, it will also exceed the max int array size both Integer.MAX_VALUE – Scary Wombat Aug 31 '16 at 02:06
-
1Please be more specific. So your file contains "1234567890...." - now what should be in your integer array [1, 2, 3, 4, ... ] or what? – GhostCat Aug 31 '16 at 02:07
-
2How many bytes is the length of your file? – Erwin Bolwidt Aug 31 '16 at 02:15
-
3Post some code with the results you get and the results expected, or you will get this question closed since it sounds like a "please do my homework" question. – laffuste Aug 31 '16 at 02:40
1 Answers
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();
}
}
}