How to read an integer from a file with words in it in Java

Viewed 40

If I had a .txt file like this:

frames: 312
speed: 100 fps
2

Circle
r: 20
x: 30
y: 35

and I wanted to get the useful information from the file, how would I do that? I'm using java.util.Scanner. I want to get all the integers, and I want to read when it skips a line and the word "Circle"

1 Answers

split it by line / loop over the lines.

If the line contains a ':' split the line by ':', this gives you an array of length 2.

Create a Map<String, Int>. Use array[0] for the map key, use array[1] for map value, check that the value can be an int ("100 fps" will fail) before adding it to the Map. Also remember to trim the whitespace.

If the line doesn't contain a ':' you can add it to a List<String>.

Lots of other ways to do it, depends on the file format consistency and what you want to use the data for etc.

You end up with:

Map:
[["frames":42], ["speed":100], ["r":20], ["x":30], ["y":35]]
List:
["2","","Circle"]
Related