How can I open a .txt file and read numbers separated by enters or spaces into an array list?
You can use a Scanner and its nextInt() method. Scanner also has nextLong() for larger integers, if needed.
Create a FileInputStream object by passing the required file (object) as a parameter to its constructor. Read the contents of the file using the read() method into a byte array. Insatiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array.
There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>(); File file = new File("file.txt"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; while ((text = reader.readLine()) != null) { list.add(Integer.parseInt(text)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { } } //print out the list System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt"); Scanner scanner = new Scanner(filePath); List<Integer> integers = new ArrayList<>(); while (scanner.hasNext()) { if (scanner.hasNextInt()) { integers.add(scanner.nextInt()); } else { scanner.next(); } }
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With