views:

131

answers:

6

I have a text file full of numbers and I want to read the numbers into Java and then make a list that I can sort. it has been a while since I have used java and I am forgetting how to do this.

the text file looks something like this

4.5234  
9.3564
1.2342
4.4674
9.6545
6.7856
+1  A: 

Short instructions without code:

  1. Create a BufferedReader to read from your file.
  2. Iterate all over the file reading line by line with reader.readLine(), until readLine() returns null (== end of file)
  3. Parse each line as a Float or Double (e.g. Float.valueOf(line) or Double.valueOf(line)
  4. Add your Float or Double objects to an ArrayList.
Grodriguez
+1  A: 

Not accounting for the fact that you need to setup exception handling and such based on your sourrounding code, it'll look something like this:

BufferedReader br = new BufferedReader(new FileReader(new File("filename.txt")));
ArrayList<Double> ald = new ArrayList<Double>();
String line;
while(true)
{
    line = br.readLine();
    if(line == null) break;
    ald.add(new Double(line));
}
Lokathor
+2  A: 

You do something like this.

EDIT: I've tried to implement the changes dbkk mentioned in his comments so the code actually will be correct. Tell me if I got something wrong.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadList {

    public static void main(String[] args) throws IOException {

        BufferedReader in = null;
        FileReader fr = null;
        List<Double> list = new ArrayList<Double>();

        try {
            fr = new FileReader("list.txt");
            in = new BufferedReader(fr);
            String str;
            while ((str = in.readLine()) != null) {
                list.add(Double.parseDouble(str));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
            fr.close();
        }

        for (double d : list) System.out.println(d);
    }

}
Octavian Damiean
Ouch. Not only long and ugly, but also forgetting to close the file.
dbkk
@dbkk: You should pay attention when downvoting for such things since A) I'm closing the file ... after the first while block and B) it's only long because I'm one of the only ones here who has surrounded the necessary parts with a try-catch block and I have also written an output part so he can actually see what's happening even commented that it is for demonstration purposes ...
Octavian Damiean
The input stream should really be closed in a `finally {}`
matt b
@Octavain. Closing the BufferedReader, but not FileReader. Not closing in `finally` block. Pointless catch block: (A) you'll see the IOException anyway and (B) you're more likely to get an exception from parsing than from I/O (and that should probably be caught inside the while loop). Why not use `for (double d : list) System.out.println(d)`? Btw, purpose of Stack Overflow is learning, not reputation hunting.
dbkk
@dbkk: I see now. Well in that case you are right then. Believe me my rep. isn't important to me and that wasn't my point when replying to you. I was thinking that I'm closing the FileReader when closing the BufferedReader. I guess I've learned my lesson. Maybe next time you could post a more in depth explanation will definitely help me. Thanks.
Octavian Damiean
@dbkk no need to close the FileReader, the `close` on the BufferedReader will take care of that.
Colin Hebert
@Colin Hebert: So I was right in thinking that then. Well none the less the edited code works too.
Octavian Damiean
@Octavian Damiean, Yes, your code is good, but even so, I'm not quite sure that's the best solution. I mean, you're going through your file manually (and with a `while ((str = in.readLine()) != null)` that is IMO dangerous and not really readable), you have to handle all the IO stuff instead of using a utility class provided for this exact goal. Anyway as I said, your code is correct and will work without major problem ;)
Colin Hebert
@Colin Hebert: Interesting. Good to know. Thanks!
Octavian Damiean
+10  A: 

You can use a Scanner on a File and use the nextDouble() or nextFloat() method.

Scanner scanner = new Scanner(new File("pathToYourFile"));
List<Double> doubles = new ArrayList<Double>();
while(scanner.hasNextDouble()){
    doubles.add(scanner.nextDouble());
}
Collections.sort(doubles);

Resources :

Colin Hebert
To be very pedantic: The OP asked for a list, not a collection :-P
DerMike
@DerMike, you're right ;) It's a list at the end, but a collection can't be sorted, I'll edit the code.
Colin Hebert
+2  A: 

This is really fun and simple if you use Guava:

final File f = new File("your/file.txt");
final List<Float> listOfFloats =
    Lists.transform(Files.readLines(f, Charset.defaultCharset()),
        new Function<String, Float>(){

            @Override
            public Float apply(final String from){
                return Float.valueOf(from);
            }
        });

And here's a similar version using Apache Commons / IO:

final File f = new File("your/file.txt");
final List<String> lines = FileUtils.readLines(f);
final List<Float> listOfFloats = new ArrayList<Float>(lines.size());
for(final String line : lines){
    listOfFloats.add(Float.valueOf(line));
}
seanizer
+1  A: 

Use java.util.Scanner:

public List<Doubles> getNumbers(String fileName) {
  List<Double> numbers = new ArrayList<Double>();
  Scanner sc = new Scanner(new File(fileName));

  while (sc.hasNextDouble()) {
      numbers.add(sc.nextDouble());
  }

  return numbers;
}
abhin4v