java - 导入文本文件

标签 java

有什么方法可以更轻松地做到这一点吗?

我正在尝试导入一个四行文件:

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/

相关文章:

java - 如何使用hadoop配置Nut 1.4?

java - 如何使用 .equals() 以外的方法比较 java 中的列表

java - quartz : How to reload jobs and triggers with org. quartz.plugins.xml.XMLSchedulingDataProcessorPlugin?

java - 分块加载 SELECT 查询的实际数据(无需再次执行相同的查询)

java - Android:Custom Retrofit Callback,我怎样才能阻止实现做它的事情

java - Eclipselink 缓存 - 在事务中保留相同的对象

java - Android:将图片保存到文件并检索它

java - 将字符串与 HashMap 中的键值进行比较时忽略大小写

java - 在 Java 代码中定位文件

java - 升级后,得到 "Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test"和 "test(s) <[]> cannot be found"