Below is how i count the number of lines in a text file. Just wondering is there any other methods of doing this?
while(inputFile.hasNext()) {
a++;
inputFile.nextLine();
}
inputFile.close();
I'm trying to input data into an array, i don't want to read the text file twice.
any help/suggestions is appreciated.
thanks
If you just want to add the data to an array, then I append the new values to an array. If the amount of data you are reading isn't large and you don't need to do it often that should be fine. I use something like this, as given in this answer: Reading a plain text file in Java
BufferedReader fileReader = new BufferedReader(new FileReader("path/to/file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you are reading in numbers, the strings can be converted to numbers, say for integers intValue = Integer.parseInt(text)