简体   繁体   中英

Convert list of values generated from file into arrays (Java)

I have some attributes of animals in a text file and I need to be able to extract the different Strings so I can put them into an Array of Arrays so that I can later add to them and edit the values etc. Here is the code I have already used to display them in a list but doesn't produce the arrays I want.

   public class FileReading {

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("Animals.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
            if(line != null) {
            System.out.println(line);
            }
        }
    } finally {
        br.close();
    }
}

It goes along the format of: Given name, what animal it is, the price, sex, colour, date brought (although on some lines there are extra attributes such as if something is poisonous , upto 7 strings on a line.

so far my program displays the values of:

  • John, Dog, 45.50, male, blue, 2013-11-02
  • Juno, Cat, 188, male, light brown, 2017-10-04, 2017-10-14
  • Ronaldo, Sppitting Cobra, 129.99, female, black, 2018-01-13

and so on for many lines that are in the text. Any help would be appreciated as I'm completely stuck as to how I would do this.

I am a little confused. Where are you declaring an array and attempting to add values to it? Something like the following:

try {
  FileReader fileReader = new FileReader(filename);
  BufferedReader bufferedReader = new BufferedReader(fileReader);
  List<String> lines = new ArrayList<String>();
  String line = null;
  while ((line = bufferedReader.readLine()) != null) {
     lines.add(line);
  }
  bufferedReader.close();    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM