Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a txt file and read numbers in Java

Tags:

java

How can I open a .txt file and read numbers separated by enters or spaces into an array list?

like image 769
nunos Avatar asked Sep 27 '10 17:09

nunos


People also ask

Which method can be used to read an integer number from a text file?

You can use a Scanner and its nextInt() method. Scanner also has nextLong() for larger integers, if needed.

How do you read a file and count the number of words in Java?

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.

How do I read a specific text file in Java?

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.


2 Answers

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); 
like image 153
dogbane Avatar answered Sep 23 '22 12:09

dogbane


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.

like image 38
Igor G. Avatar answered Sep 24 '22 12:09

Igor G.