sblck
sblck

Reputation: 137

reading and writing text file with arraylist

I'm having problem reading text file into arraylist with multiple data types.

The file format looks like:

Name1 900 20

Name2 750 30

Name3 880 25

Name4 260 15

My list format is name + score + age and I don't know how to store the data from txt into list properly. Also I want to rewrite the file after adding some data.

Upvotes: 0

Views: 2609

Answers (2)

PermGenError
PermGenError

Reputation: 46398

If your List accepts String:

BufferedReader reader = new BufferedReader(new FileReader("yourfile.txt"));
List<String> list = new ArrayList<>();
String line=null;
while((line= reader.readLine())!=null) {
list.add(line);
}

however, it'd be better if you had a class with name, socre and age as properties and create an list of that class and split your text file with white spaces .

class SomeClass {
private String name; 
private long score;
private int age;
//getters and setters for your properties

}

now your List would be:

   List<SomeClass> list = new ArrayList<>();

and after reading the line from the file, split it based on whitespace.

 String[] arr =line.split("\\s+");
 SomeClass obj = new SomeClass();
 obj.setName(arr[0]);
 obj.setScore(Long.parseLong(arr[1]));
 obj.setAge(Integer.parseInt((arr[2]));
 list.add(obj);

Upvotes: 2

NPE
NPE

Reputation: 500167

You could create a class that would encapsulate name+score+age, and create an ArrayList of that class.

Upvotes: 2

Related Questions