Fill a vector with the data of a file.txt

1

I have a class named Gun, which has as attributes two integers and a string, I would like to make a vector of type Gun and that each position is filled with the data of a file for example that the .txt file contains:

25,20,Pistol

so that the position 0 the first integer receives 25, the second 20, and the string "pistol".

if possible? thanks in advance

    
asked by Lorenzo Zuluaga 26.05.2016 в 23:50
source

1 answer

1

Assuming you have a class like the following:

class Gun {
  int A, B;
  String C;

  public Gun(int A, int B, String C) {
    this.A = A;
    this.B = B;
    this.C = C;
  }

  //////// Éstos son métodos auxiliares, ignorar.
  // Constructor para prueba
  public Gun(String[] line) {
    this.A = Integer.parseInt(line[0]);
    this.B = Integer.parseInt(line[1]);
    this.C = line[2];
  }

  // Método para obtener la representación en string
  // del objeto...
  public String getText(){
    return A + "," + B + "," + C;
  }
}

One way, of the several that exist, to write and read text from / to a file is as follows:

public static void main(String... args) {
  // El "vector" de guns
  List<Gun> guns = new ArrayList() {{
      add(new Gun(1, 1, "A"));
      add(new Gun(2, 2, "B"));
      // ...
  }};

  // Escribir a un archivo
  try (PrintWriter writer = new PrintWriter("guns.txt", "UTF-8")) {
    guns.forEach(gun -> writer.println(gun.getText()));
  } catch (IOException ex) {
    System.out.println(ex);
  }

  guns.clear();

  // Leer de ese mismo archivo
  try (BufferedReader in = new BufferedReader(new FileReader("guns.txt"))) {
    for (String s = in.readLine(); s != null; s = in.readLine())
      guns.add(new Gun(s.split(",")));
  } catch (IOException ex) {
    System.out.println(ex);
  }

  guns.forEach(gun -> System.out.println("Gun: " + gun.getText()));
}

If you are interested in saving information about your objects, another possible solution would be to serialize.

    
answered by 27.05.2016 в 19:18