Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a list out of a text file in java?

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
like image 398
Ben Fossen Avatar asked Oct 04 '10 08:10

Ben Fossen


People also ask

How do I read a text file into an ArrayList?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.

How do I convert a text file to an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.


2 Answers

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 :

  • Javadoc - Scanner.nextDouble()
like image 153
Colin Hebert Avatar answered Sep 26 '22 08:09

Colin Hebert


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);
    }

}
like image 33
Octavian A. Damiean Avatar answered Sep 26 '22 08:09

Octavian A. Damiean