How to read an array of integers from a text file, where each number is written in a new line?
- Give at least the file format. Numbers can be separated by a space, line by line .. Is there any more like a binary file with an array of ints? - vp_arth
- @vp_arth, are you a programmer? And in JS and Java ... where will I meet you ?) - Yuri
- @Yuri, yes anywhere) We can all) - vp_arth
- @vp_arth, you are an interesting person. I would talk to you. Check out my chat ( chat.stackexchange.com/rooms/52027/communication-with-the-yuri ) like something :) - Yuri
- oneDescribe the solution to the problem in more detail so that you can give a normal answer. - Yuri
|
1 answer
You can use Scanner for this:
try (Scanner scanner = new Scanner(new File("in.txt"))) { ArrayList<Integer> numbers = new ArrayList<>(); while (scanner.hasNextInt()) { numbers.add(scanner.nextInt()); } System.out.println(numbers); } catch (FileNotFoundException e) { e.printStackTrace(); } If necessary, you can create an array based on the resulting list:
Integer[] array = numbers.toArray(new Integer[0]); |