I am reading values in a text file one by one without any problem in Java. The file has integer values as shown below:
2 3
5 6 7 8 9
12 13 15 18 21 26 55
16 24 45 58 97
I need to read just a single line values instead of reading all values and there is an example on How to get line number using scanner, but I am looking a solution without using LineNumberReader
and using a counter by looping all lines. Instead, it would be good to get the line number via scanner method that I already use to read values. Is it possible?
Here is the method I try to create:
public static List<Integer> getInput(int lineIndex) throws FileNotFoundException{
List list = new ArrayList<Integer>();
Scanner scan = new Scanner(new File(INPUT_FILE_NAME));
int lineNum=0;
//s = new Scanner(new BufferedReader(new FileReader("input.txt")));
while(scan.hasNextLine()) {
if(lineNum == lineIndex) {
list.add(scan.nextInt()); //but in this case I also loop all values in this line
}
lineNum++;
}
scan.close();
return list;
}