I want to read a text file and store its contents in an array where each element of the array holds up to 500 characters from the file (i.e. keep reading 500 characters at a time until there are no more characters to read).
I'm having trouble doing this because I'm having trouble understanding the difference between all of the different ways to do IO in Java and I can't find any that performs the task I want.
And will I need to use an array list since I don't initially know how many items are in the array?
It would be hard to avoid using ArrayList or something similar. If you know the file is ASCII, you could do
But if the file uses a variable-width encoding like UTF-8, this won't work. This code will do the job.
Note that
FileReader
uses the platform default encoding. To specify a specific encoding, replace it withnew InputStreamReader(new FileInputStream(fname), charSet)
. It bit ugly, but that's the best way to do it.