读取 TextFile 并存储在数组上
Reading TextFile and storage on an Array
我有一个数据结构课程的任务对我来说变得越来越复杂。指令是读取一个文本文件,格式为:Ana,30,120|Raul,23,178|Laura,15,164;
(with 200 elements),其中第一个值是名字、第二个年龄,第三个身高。我必须添加到 ArrayList。
我有以下代码:
public void readFile()
{
String lineas;
try
{
InputStream fileInputStream = new FileInputStream("datos.txt");
InputStreamReader reader = new InputStreamReader(fileInputStream, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(reader);
while((lineas = br.readLine()) != null)
{
String[] valor = lineas.split(",");
String name = valor[0];
int age = Integer.parseInt(valor[1]);
int height = Integer.parseInt(valor[2]);
persona.add(new Persona(name, age, height));
showMenuOptions();
}
} catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
} catch (IOException ex) {
System.out.println("Can't open the File.");
}
}
但它只在找到时通过在末尾分隔每一行来执行搜索,但是我需要修改以便它检测由 ,
分隔的每个值并在找到字符时将它们分隔 |
.
参考下面link,可以使用split()
方法
Java reading a file into an ArrayList?
public List<Person> loadPeopleFromFile(String path) {
List<Person> result = new ArrayList<>();
try {
try (Scanner s = new Scanner(new File(path))) {
s.useDelimiter("[|,;]");
while (s.hasNext()) {
result.add(new Person(s.next(), s.nextInt(), s.nextInt()));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
应该给你做的
我有一个数据结构课程的任务对我来说变得越来越复杂。指令是读取一个文本文件,格式为:Ana,30,120|Raul,23,178|Laura,15,164;
(with 200 elements),其中第一个值是名字、第二个年龄,第三个身高。我必须添加到 ArrayList。
我有以下代码:
public void readFile()
{
String lineas;
try
{
InputStream fileInputStream = new FileInputStream("datos.txt");
InputStreamReader reader = new InputStreamReader(fileInputStream, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(reader);
while((lineas = br.readLine()) != null)
{
String[] valor = lineas.split(",");
String name = valor[0];
int age = Integer.parseInt(valor[1]);
int height = Integer.parseInt(valor[2]);
persona.add(new Persona(name, age, height));
showMenuOptions();
}
} catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
} catch (IOException ex) {
System.out.println("Can't open the File.");
}
}
但它只在找到时通过在末尾分隔每一行来执行搜索,但是我需要修改以便它检测由 ,
分隔的每个值并在找到字符时将它们分隔 |
.
参考下面link,可以使用split()
方法
Java reading a file into an ArrayList?
public List<Person> loadPeopleFromFile(String path) {
List<Person> result = new ArrayList<>();
try {
try (Scanner s = new Scanner(new File(path))) {
s.useDelimiter("[|,;]");
while (s.hasNext()) {
result.add(new Person(s.next(), s.nextInt(), s.nextInt()));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
应该给你做的