Read from a text file in Java and store each item in a different variable

Viewed 30

I've got a text file which has constants and its value defined in it in separate lines For e.g.

s, 2.1
v, 3.7

I get how to extract this in Java, but how do I store each value against it in a seperate variable.

For e.g. I need to use the value of s to computer something and value of v in a operate equation to calculate something ?

2 Answers

If you are expecting same input every time and have created variables for the same in your code then it can be

    Float s, v;
    s = Float.parseFloat(line.split(",")[1]);
    //read next line
    v = Float.parseFloat(line.split(",")[1]);

And if you want to keep it dynamic not knowing which key value pair would appear then you can put it in Map as @Rogue mentioned

You can use BufferedReader class.

File file = new File("..path");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null){
   Map<String, Double> map = new HashMap<>();
   String str[] = st.split(",");
   map.put(str[0], Double.parseDouble(str[1]));
}

  
Related