-2

I have a text file in which the data is mentioned as below.

3
4
5
6

Now i want to make a function in which i first take the value 3 and then make another function in which i need the value 4.

I have this code which reads the file line by line. But my question is how should access the integers in each line and then store it in any variable so that i can use it in my function?

  try {

        File f = new File("src/txt.txt");

        BufferedReader b = new BufferedReader(new FileReader(f));

        String readLine = "";

        System.out.println("Reading file using Buffered Reader");

        while ((readLine = b.readLine()) != null) {


            System.out.println(readLine);


        }

    } catch (IOException e) {
        e.printStackTrace();
    }
Ahsan Asif
  • 31
  • 8

1 Answers1

0

You could try something like this I suppose:

public class Main {

    static List<Integer> integers = new ArrayList<>();
    public static void main(String[] args) {
        try(BufferedReader reader = new BufferedReader(new FileReader(Paths.get("filepath").toFile()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    integers.add(Integer.valueOf(line));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    integers.add(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

With this you'll have all the numbers you've read successfully in a list that can be used for any purposes.

akortex
  • 5,067
  • 2
  • 25
  • 57