I asked for more detailed help on this. But again I need help. I first worked in the compiler to read my file. Later, when I moved my code to the project, other problems arose. I had to use the getAssets() method to read the file. As a result, can you help me to create the same list again?
What I want to do is create a List<List<Double>>
list. I am creating the same list as below but as List<String>
.
The problem : when reading the file it takes each line as a string . for example "-0.140625000000000,0.986816000000000,-0.209473000000000"
My text file
-0.140625000000000,0.986816000000000,-0.209473000000000
-0.144531000000000,0.959473000000000,-0.262207000000000
-0.168945000000000,0.945312000000000,-0.340820000000000
-0.141602000000000,0.939453000000000,-0.289551000000000
-0.145508000000000,0.950195000000000,-0.305664000000000
-0.147461000000000,0.946777000000000,-0.302246000000000
-0.146484000000000,0.950684000000000,-0.305176000000000
-0.145996000000000,0.951660000000000,-0.305176000000000
....
For Example
List<List<double>> list = [
[-0.447266000000000, 0.417969000000000, 0.738770000000000],
[-0.447266000000000, 0.417969000000000, 0.738770000000000],
[-0.447266000000000, 0.417969000000000, 0.738770000000000],
[-0.447266000000000, 0.417969000000000, 0.738770000000000],
[-0.447266000000000, 0.417969000000000, 0.738770000000000]
]
My code
The code I got in the comment line was my old working code.
public void myPatienListMethod() {
List<List<Double>> myList = new ArrayList<>();
List<String> myLists = new ArrayList<>();
//try (CSVReader reader = new CSVReader( new FileReader(fileName))) {
//List<String[]> r = reader.readAll();
// r.forEach(lineArr -> {
// List<Double> line = new ArrayList<>();
// for (String str : lineArr) {
// line.add(Double.parseDouble(str));
// }
// myList.add(line);
// });
// }
String filename = "aaa.txt";
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader
(this.getAssets().open(filename)));
String line;
while ((line = bufferedReader.readLine()) != null) {
myLists.add(line);
// Log.i("list", myLists.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CodePudding user response:
I am sure there is already an answer to this, but i can't find it. You need to first split the line by the delimiter(looks like comma).
String[] strings = line.split(",");
Then you need to iterate the strings, parse each string to double and add it to the list.
List<Double> parsedLine = new ArrayList<>(strings.length);
for (String string : strings) {
parsedLine.add(Double.parseDouble(string));
}
Or you can do the same with java 8 stream:
List<Double> parsedLine = Arrays.stream(line.split(","))
.map(Double::parseDouble)
.collect(Collectors.toList());