简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM