我对编程相当陌生,最近我写了一些东西来利用扫描仪类从文本文件填充对象数组。本质上,我可以重写这个文本文件或添加新信息,而不必更改代码。我想我的问题是:有没有更简单/更优选的方法来做到这一点?我正在尝试学习编码的细微差别。
import java.io.*;
import java.util.*;
public class ImportTest {
public static void main(String[] args) throws IOException
{
Scanner s = null;
Scanner k = null;
ArrayList myList = new ArrayList<String>();
ArrayList myList2 = new ArrayList<String>();
ArrayList myList3 = new ArrayList<Student>();
try
{
s = new Scanner(new BufferedReader(new FileReader("testMe.txt")));
while (s.hasNext())
{
myList.add(s.nextLine());
}
}
finally
{
if (s != null)
{
s.close();
}
}
System.out.println("My List 1:");
for(int i=0; i<myList.size(); i++)
{
System.out.println(i+". "+myList.get(i));
}
for(int x=0; x<myList.size(); x++)
{
try
{
k = new Scanner(myList.get(x).toString());
while (k.hasNext())
{
myList2.add(k.next());
}
}
finally
{
if (k != null)
{
k.close();
}
}
String name;
int age;
double money;
name=myList2.get(0).toString();
age=Integer.parseInt(myList2.get(1).toString());
money=Double.parseDouble(myList2.get(2).toString());
Student myStudent=new Student(name, age, money);
myList3.add(myStudent);
myList2.clear();
}
System.out.println("Test of list object: ");
for(int i=0; i<myList3.size(); i++)
{
System.out.println(i+". "+myList3.get(i).toString());
}
}
}
最佳答案
我会逐行读取文件并直接解析每一行。这样您就不需要 3 个列表、2 个扫描仪和多次迭代:
String line = "";
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
ArrayList<Student> students = new ArrayList<Student>();
while( (line = br.readLine()) != null)
{
String[] tmp = line.split("\\s+"); //split line by spaces
//this needs bounds & error checking etc.
students.add(new Student(tmp[0], Integer.parseInt(tmp[1]), Double.parseDouble(tmp[2])));
}
在 Java 7 中,您可以使用 new file functions一次读取所有行:
List<String> allLines = Files.readAllLines("test.txt", Charset.defaultCharset());
不要忘记关闭阅读器或使用 try-with-resources (从java 1.7开始)
关于java - 利用扫描仪填充对象数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20988613/