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
}
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();
}
Use a Scanner instead!
I would use a scanner and read line by rather than char by char and then store it as a string. If you really want a char array it's easier to get it out afterwards.
This functionally does the same thing:
String theString = "";
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
theString = scanner.nextLine();
while (scanner.hasNextLine()) {
theString = theString + "\n" + scanner.nextLine();
}
char[] charArray = theString.toCharArray();
The upside to this is that you get to take advantage of Java's String type which handles all of the nasty length and concatenation business for you. And the the String.toCharArray() method is already built in to return an array that's automatically sized the way you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With