Skip to content
Advertisement

Read integers from a text file and store them into an array in Java

So I have a text file with integers in it like this:

20 25 3 239 6 184 211 155 245 25 13 73 73 82 70 164 164 102 193 44 205 250 145 102 95 83 152 168 148 193 54 228 86 244 10 26 181 106 53 209 249 21 150 213 92 234 135 121 54 8 241 252 68 169 165 159 182 56 58 158 72 15 19 10

How can I read the file with above integers and store them into an array starting with 20 and ending with 10.

Advertisement

Answer

You can use java’s file nio.file api to read file data into string and then split that string using space to String[] and convert each number from String to an int in this array.

String fileData = new String(Files.readAllBytes(Path.of("file path here")));
int[] data = Stream.of(fileData.split(" ")).mapToInt(Integer::parseInt).toArray();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement