Skip to content
Advertisement

Reading a file and saving each line into a variable

For a project of mine, I’m trying to read a file of Integers and save each line into a file. Each of the files I’m reading have a different amount of lines.

The file would look like

17
72
61
11
63
95
100

Is there a way I can use a loop and save the value in a different variable for each line?

Advertisement

Answer

Create a Collection to capture your values. We can use a List so we maintain the input order.

List<Integer> list = new ArrayList<>();

Create a mechanism for reading from the file. A common option is a Scanner. The Scanner is Autoclosable so we’ll put it in a try-with-resources block so we don’t have to close it ourselves.

try (Scanner scanner = new Scanner(new File(fileName))) {
  ... do stuff ...
}

While the Scanner has values, read a value and add it to the List.

while (scanner.hasNextInt()) {
  list.add(scanner.nextInt());
}

In sum…

List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(yourFileName)) {
  while (scanner.hasNextInt()) {
    list.add(scanner.nextInt());
  }
}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement