I am trying to save data in a text file to an array containing doubles. I have made it work for integers, but I want to add non integer data and so far I can't figure out. Here is my code so far:
public class MainClass {
public static void main(String[] args) throws FileNotFoundException {
List<Double> E0 = Arrays.asList();
List<Double> E1 = Arrays.asList();
List<Double> E2 = Arrays.asList();
List<Double> C = Arrays.asList();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("C:\\Data.txt"));
String line = reader.readLine();
while (line != null) {
Double lineParts = line.split(",");
E0.add(lineParts[0]);
E1.add(lineParts[1]);
E2.add(lineParts[2]);
C.add(lineParts[3]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(E0);
System.out.println(E1);
System.out.println(E2);
System.out.println(C);
}
}
Here is my data:
1,1,4,-1
1,2,9,1
1,5,6,1
1,4,5,1
1,6,7,-1
1,1,1,-1
The complete answer to your question is to convert the static separating method with full dynamic parsing method without any error, This answer is safest possible solution that doesn't depend on how long is your inserted data.
you can achieve this with the help of a list containing list of double values
Sample with your data:
List<List<Double>> lines = new ArrayList<>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("C:\\Data.txt"));
String line = reader.readLine();
while (line != null) {
List<Double> lineList = new ArrayList<>();
String[] lineParts = line.split(",");
for (String linePart : lineParts) {
lineList.add(Double.valueOf(linePart));
}
lines.add(lineList);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(lines);
}
Regards :)