40

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nunos
  • 20,479
  • 50
  • 119
  • 154

6 Answers6

63

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);
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • This is good, but I would use `Integer.valueOf(String)` instead since you want an object (Integer) anyway. – Mark Peters Sep 27 '10 at 17:38
  • Why can't we move **reader.close();** to the line right after the while loop and avoid the entire **finally** block and the other **try-catch** block the **finally** contains ? – M-D Oct 01 '13 at 16:20
  • 2
    @m-d See the [Java Tutorial](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html). You should close resources in a `finally` to ensure that they are always closed even if an exception occurs within the `try` block. This prevents resource leaks. – dogbane Oct 02 '13 at 07:34
  • is file opening a resource intensive task ? – Rishabh Dhiman Aug 26 '19 at 05:52
  • Running this with 'try-with-resources' is also an added bonus: https://stackoverflow.com/a/1388772/8065149 – cjnash Dec 03 '20 at 04:35
23

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.

Igor G.
  • 6,955
  • 6
  • 26
  • 26
11

Good news in Java 8 we can do it in one line:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
3
   try{

    BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }finally{
     in.close();
    }

This will read line by line,

If your no. are saperated by newline char. then in place of

 System.out.println (strLine);

You can have

try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}  

If it is separated by spaces then

try{
    String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
    }catch(NumberFormatException npe){
    //do something
    }  
jmj
  • 237,923
  • 42
  • 401
  • 438
  • you should close the inputstream in a `finally` block. – dogbane Sep 27 '10 at 17:18
  • Please don't use DataInputStream to read text. Unfortunately examples like this get copied again and again so can you can remove it from your example. http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html – Peter Lawrey Jan 30 '13 at 23:44
3
File file = new File("file.txt");   
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        integers.add(scanner.nextInt());
    } 
    else {
        scanner.next();
    }
}
System.out.println(integers);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ban
  • 339
  • 1
  • 5
  • 16
0
import java.io.*;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileWriter  fin=new FileWriter("testout.txt");    
            BufferedWriter d = new BufferedWriter(fin);
            int a[] = new int[3];
            a[0]=1;
            a[1]=22;
            a[2]=3;
            String s="";
            for(int i=0;i<3;i++)
            {
                s=Integer.toString(a[i]);
                d.write(s);
                d.newLine();
            }

            System.out.println("Success");
            d.close();
            fin.close();    



            FileReader in=new FileReader("testout.txt");
            BufferedReader br=new BufferedReader(in);
            String i="";
            int sum=0;
            while ((i=br.readLine())!= null)
            {
                sum += Integer.parseInt(i);
            }
            System.out.println(sum);
          }catch(Exception e){System.out.println(e);}    
         }    
        }  

OUTPUT:: Success 26

Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.