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
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.
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.
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 :
Scanner.nextDouble()
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With