Aasam Tasaddaq Aasam Tasaddaq - 20 days ago 6
Java Question

Reading text file into a char array in Java

I am reading a text file and trying to store it into an array char by char. My approach (below) pre-defines a

char
array with an initial length of 100000 (my main issue here). So, if the file contains characters less than that amount (problem also if more characters than that), then there are nulls in my array. I want to avoid that. Is there a way to predetermine the amount of characters present in a text file? Or is there a better approach altogether to store the file char by char?

char buf[] = new char[100000];
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
br.read(buf);
for(int i = 0; i < buf.length; i++)
{
//Do stuff here
}

Answer

Use an ArrayList of Characters to accept the values. After that convert ArrayList to an Array as

 char[] resultArray = list.toArray(new char[list.size()]);

You should use br.readLine() instead of br.read() as follows:

String str;
while((str = br.readLine())!=null){
        str.tocharArray();
}