In Java, if you know for certain a file is very small, you can use readBytes()
method to read the content in one go instead of read it line by line or using buffer.
Process the lines inside the loop instead of after it. If you really need the file in a variable:
var=$(<file)
Another alternative is to use the nice mapfile builtin:
mapfile < test.file
echo "${MAPFILE[@]}"
As another option, you can build an array of lines. If you're running bash 4+, you can use the mapfile
builtin:
mapfile -t lines <test.file
If you want the lines to be output as well as stored you could do something like this:
mapfile -t lines < <(tee /dev/tty <test.file)
Then "${lines[0]}"
will be the first line of the file, "${lines[1]}"
the second, and so on. ${#lines[@]}
will be the number of lines; "${lines[@]}"
will be the whole array, while "${lines[*]}"
will be the lines joined together with spaces into one big string.
For older versions of bash, you can build the array manually:
lines=()
while IFS= read -r line
do
printf '%s\n' "$line"
lines+=("$line")
done < test.file