views:

466

answers:

4

I want to read a text file containing space sepearted values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of the text file:

1 62 4 55 5 6 77

I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]. How can I do it in Java?

+14  A: 

You can use java.io.BufferedReader to read a file line by line.

BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
    // ...
}

Tutorial: http://java.sun.com/docs/books/tutorial/essential/io/charstreams.html


You can use String#split() to split a String in parts.

String[] parts = line.split("\\s");

Tutorial: http://java.sun.com/docs/books/tutorial/java/data/manipstrings.html


You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part);

Tutorial: http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html


You can use List#add() to add an element to a List.

list.add(i);

Tutorial: http://java.sun.com/docs/books/tutorial/collections/index.html

BalusC
thanks man: IT was of great help
aks
+10  A: 

Java 1.5 introduced the Scanner class for handling input from file and streams.

Its use for getting integers from a file would look something like this.

ArrayList<Integer> integers = new ArrayList<Integer>();    
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

Check the API though. There are many more options for dealing with different types of input sources, differing delimeters, and differing data types.

tschaible
A: 

look at this example an try to do your own

import java.io.*;

public class ReadFile {

    public static void main(String[] args){
        String string="";
        String file ="textFile.txt";

        //reading   
        try{
            InputStream ips=new FileInputStream(fichier); 
            InputStreamReader ipsr=new InputStreamReader(ips);
            BufferedReader br=new BufferedReader(ipsr);
            String line;
            while ((ligne=br.readLine())!=null){
                System.out.println(line);
                string+=line+"\n";
            }
            br.close(); 
        }       
        catch (Exception e){
            System.out.println(e.toString());
        }

        //writing
        try {
            FileWriter fw = new FileWriter (file);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter fileOut = new PrintWriter (bw); 
                fileOut.println (string+"\n test of read and write !!"); 
            fileOut.close();
            System.out.println("the file " + file + " is created!"); 
        }
        catch (Exception e){
            System.out.println(e.toString());
        }       
    }
}
tuxou
A: 

Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Commons IO and Google Collections).

String text = FileUtils.readFileToString(new File("textfile.txt"));
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
    list.add(Integer.valueOf(s));
}

Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

Drawback: you obviously may not want to add the library dependencies just for this. (Especially Google Collections just for Lists! Then again, you'd be silly not to make use of Google Collections in your projects. ;-)

Jonik
Jonik
yes +1 @Jonik!!
tuxou
@tuxou: +1, eh? Are you sure? No one voted this either way. :)
Jonik
@Jonik:+1, yours too lol
tuxou