Search code examples
javatextfieldbuffered

How to store different parts of a text file into different variables?


I am trying to read parts of a text file with the format

John Smith
72
160

The first line being the name (string), and the second and third lines being height and weight (both ints). However, I cannot find a way to store each of these into their own variables, instead I can only figure out how to store the whole thing into one variable and print it. This is the code that I have as of now

        try
    {
        File file = new File("person.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
            while ((line = bufferedReader.readLine()) != null)
            {
               stringBuffer.append(line);
               stringBuffer.append("\n");
            }
        fileReader.close();
        System.out.println(stringBuffer);
    }

In this part

stringBuffer.append(line);
stringBuffer.append("\n");

I was thinking of trying to add a part in the middle of both those lines that stored a variable, but it did not seem possible. I also thought of using a for loop and using that to my advantage somehow, but could not figure out a way to do it with that either.

Is there any possible way to do this that I do not know about? Thank you


Solution

  • Reading and parsing a text file in Java has been getting easier in every new version. You can try the following way:

    List<String> lines = Files.lines(Paths.get("person.txt")).collect(Collectors.toList());
    String name = lines.get(0);
    Integer height = Integer.parseInt(lines.get(1));
    Integer weight = Integer.parseInt(lines.get(2));