Skip to content
Advertisement

How to save information separately form .txt into multiple strings in Java

I have a mydata.txt, where I want to read in information separately.

The 1st row save as “zoo number”, “animal number”

the 2nd row till the 5th row save as “data for animals in matrix”

the 6th row save as dog “number” “appetite” “weight” “height”

2 83
30 50 21 42 0 3 
55 56 78 34 2 1
87 76 23 21 3 2
88 22 56 78 32 8
dog 23 79 67 21

The code I written as below, however, my code only be able to reload everything form mydata.txt into a string. But I want to save those information separately into individual string (for that matrix) and variables (E.g. dog’s number, dog’s sappetite…) . How can I do that?

 private void readFile(String fileName){

        try{

            File file = new File("myData.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer=new StringBuffer();   

            String line = bufferedReader.readLine();

            while ((line = bufferedReader.readLine()) != null)  {
                stringBuffer.append(line);     
                stringBuffer.append("n");  
            }

            fileReader.close();
            bufferedReader.close();

            System.out.println("Contents of File: ");
            System.out.println(stringBuffer.toString());  

        }catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

Advertisement

Answer

Here you should use split method from String class.

  String[] rowOne = line.split(" ");
  int zooNumber = Integer.valueOf(rowOne[0]);
  int animalNumber = Integer.valueOf(rowOne[1]);

So when you split with " " will give you array for String splitted by spaces. Then reading Index by Index will give you desired values.

Updated Answer: You can get value row by row as below :

int i = 1;

      while ((line = bufferedReader.readLine()) != null) {

        if (i == 1) {
          String[] rowOne = line.split(" ");
          int zooNumber = Integer.valueOf(rowOne[0]);
          int animalNumber = Integer.valueOf(rowOne[1]);
        } else if(i > 1 && i < 6) {
          String[] midRows = line.split(" ");
          // retrieve values at index 0, 1, 2, 3, 4 ,5
          // First 2nd Row
          // Index 0 : 30
          // Index 1 : 50
          //,...
        } else if(i == 6) {
          String[] midRows = line.split(" ");
          // retrieve values at index 0, 1, 2, 3, 4
          // First 6th Row
          // Index 0 : dog
          // Index 1 : 23
          //,...
        } else {
          break;
        }
        i++;
      }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement