简体   繁体   English

用arraylist读写文本文件

[英]reading and writing text file with arraylist

I'm having problem reading text file into arraylist with multiple data types. 我在将文本文件读取到具有多种数据类型的arraylist时遇到问题。

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. 我的列表格式是name + score + age ,我不知道如何将txt中的数据正确存储到列表中。 Also I want to rewrite the file after adding some data. 我也想在添加一些数据后重写文件。

您可以创建一个封装名称+得分+年龄的类,并创建该类的ArrayList

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 . 但是,最好有一个以name,socre和age作为属性的类,并创建该类的列表,并用空格分隔文本文件。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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