Search code examples
javaarraysbufferedreader

Read Text file to java object array


I want a method or an example to read data from text file and store them into array of object. Each object has attributes (month name, number and boolean array[3]).

The text file contains this information(Month's name, number and boolean array) line by line:

May
211345
true false true
June
8868767
false true false

The classes:

public class A{
  private String monthName;
  private int number;
  private boolean[] working;

  public data() { ... }
}

publlic class B {
  private A[] a;
}

Solution

  • Here is one way to read the file line-by-line and parse the fields. This assumes that the data file is correct, though (no missing fields, fields are in the correct format, etc.). You have to add code to create the object and add it to an array.

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    
    public class ReadFile {
    
        public static void main(String[] args) {
    
            String fileFullPath = "C:\\Temp\\data.txt";
    
            /** verify that file exists */
            File checkFile = new File(fileFullPath);
            if (!checkFile.exists()) {
                System.err.println("error - file does not exist");
                System.exit(0);
            }        
    
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(fileFullPath));
                String line;
    
                /** keep reading lines while we still have some */
                String month;
                int number;
                boolean[] barr;
    
                while ((line = br.readLine()) != null) {
                    month = line;
    
                    line = br.readLine();
                    number = Integer.parseInt(line);
    
                    line = br.readLine();
                    String[] arr = line.split("\\s");
                    barr = new boolean[3];
                    for (int i=0; i < arr.length; i++) {
                        barr[i] = Boolean.parseBoolean(arr[i]);
                    }
    
                    /** store the fields in your object, then add to array **/
                    System.out.println(month);
                    System.out.println(number);
                    System.out.println(Arrays.toString(barr));
                    System.out.println();
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        } //end main()
    
    } //end