-2

Say for example the file I'll be reading off of will be:

5, 6

2, 1

3, 5

7, 9

1, 0

0, 0

I first would like to store the integer 5 into variable 'a' and then integer 6 into variable 'b', and then I would like to use them in a method. I then would like to store the second line, 2 into variable 'a' and 1 into variable 'b'. So basically reuse just two, 'a' and 'b', to use them temporarily in a method and store the next line of input into those variables, and so on. In Java, how can I go about doing so with file reading?

user3466314
  • 37
  • 2
  • 8
  • Possible duplicate of http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java – DeiAndrei Sep 17 '14 at 09:04
  • Whilst not semantically an exact duplicate, the answer given for that question will apply here also, and is of better quality than those provided so far. – Guy Flavell Sep 17 '14 at 09:09

1 Answers1

0
BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\testing.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            String [] split = sCurrentLine.split(",");
            String a = split[0];
            String b = split[1];
            your_method(a,b);

        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

If you need the values as Integers, you can use

int aInt = Integer.parseInt(a);
int bInt = Integer.parseInt(b);
conFusl
  • 919
  • 6
  • 12