有什么方法可以更轻松地做到这一点吗?
我正在尝试导入一个四行文件:
name phone mobile address
I'm using:
public void importContacts() {
try {
BufferedReader infoReader = new BufferedReader(new FileReader(
"../files/example.txt"));
int i = 0;
String loadContacts;
while ((loadContacts = infoReader.readLine()) != null) {
temp.add(loadContacts);
i++;
}
int a = 0;
int b = 0;
for (a = 0, b = 0; a < temp.size(); a++, b++) {
if (b == 4) {
b = 0;
}
if (b == 0) {
Name.add(temp.get(a));
}
if (b == 1) {
Phone.add(temp.get(a));
}
if (b == 2) {
Mobile.add(temp.get(a));
}
if (b == 3) {
Address.add(temp.get(a));
}
}
}
catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
txtName.setText(Name.get(index));
txtPhone.setText(Phone.get(index));
txtMobile.setText(Mobile.get(index));
txtAddress.setText(Address.get(index));
}
他们的方法更简单吗?看起来很啰嗦!
最佳答案
您可以使用扫描仪类。
Scanner s = new Scanner(new File("input.txt"));
name = s.nextLine();
phone = s.nextLine();
mobile = s.nextLine();
address = s.nextLine();
关于java - 导入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1786010/