开发者

importing a text file

any way easier to do this??

i'm trying to import a file which is four lines:

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

}

is their an easier way? looks long winded!


You can use the Scanner Class.

Scanner s = new Scanner(new File("input.txt"));
name = s.nextLine();
phone = s.nextLine();
mobile = s.nextLine();
address = s.nextLine();


Apache Fileutils readFileToString() or readLines() makes the code more clean.

    import org.apache.commons.io.FileUtils;

    ...


    File file = new File("foobar.txt");

    try
    {
        List<String> data = FileUtils.readLines(file);

        // Iterate the result to print each line of the file.
        Iterator<String> iter = data.iterator();
        while(iter.hasNext()) {
            Name.add(iter.next());
            if (iter.hasNext()) {
                Phone.add(iter.next());
            }
            if (iter.hasNext()) {
                Mobile.add(iter.next());
            }
            if (iter.hasNext()) {
                Address.add(iter.next());
            }
        }

    } catch (IOException e)
    {
        e.printStackTrace();
    }

You could even make it a bit shorter by using a construction like

if (iter.hasNext()) Phone.add(iter.next());

but personally I feel that discarding braces makes code more error-prone. You could put it on one line, though.


Create a data object representing your set of data. With the new object, take in a string and parse it locally in the new object.

Driver Class: 
  readInFromFile 

EntityClass
  EntityClass(String) < calls the parse method
  get[data elements]
  parseFromString(String info) <- this is responsible for all of your reading

The "readFromFile" method will turn into:

....
while ((String line= reader.readLine) != null) {
   list.add(new Entity(line));
}


BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));

    String loadContacts;
    List<People> list = new ArrayList<People>();

    while ((loadContacts = infoReader.readLine()) != null) {
        String[] singleContact = loadContacts.split(REGEXP_FOR_SPLIT_VALUES);
        People p = new People();
        p.setName(singleContact[0]);
        p.setPhone(singleContact[1]);
        p.setMobile(singleContact[2]);
        p.setAddress(singleContact[3]);
        list.add(p);
    }


How about this?

while(infoReader.hasNext()) {
  Name.add(infoReader.readLine());
  Phone.add(infoReader.readLine());
  Mobile.add(infoReader.readLine());
  Address.add(infoReader.readLine());
}

although I'd prefer changing the Name, Phone etc classes to be one class representing one contact.


Here's how I would do it, using the new Scanner class to read easily and take care of IOExceptions, using the ClassLoader to find the file, and using a simple @Data class to store the data.

public void importContacts() {
    Scanner scanner = new Scanner(ClassLoader.getSystemClassLoader().getResourceAsStream("example.txt"));
    List<Contact> list = Lists.newArrayList();
    while(scanner.hasNext()) {
        list.add(new Contact(
            scanner.nextLine(),
            scanner.nextLine(),
            scanner.nextLine(),
            scanner.nextLine()
        ));
    }

    Contact c = list.get(index);
    txtName.setText(c.getName());
    txtAddress.setText(c.getAddress());
    txtPhone.setText(c.getPhone());
    txtMobile.setText(c.getMobile());
}

private static @Data class Contact {
    private final String name, phone, mobile, address;
}


If the file will only ever contain one contact and you have control over the format of the source text file you could reformat it like a properties file:

name=value

Then you'd read it in as a properties file (see ResourceBundle), which ends up being simple:

Mobile.add(properties.getProperty("mobile"))


Why not just:

public String readLine(BufferedReader pReader) {
    try {
        return pReader.readLine();
    } catch(IOException IOE) {
        /* Not a very good practice but let say "We don't care!" */
        // Return null if the line is not there (like there was no 4 lines in the file)
        return null;
    }
}

public void importContacts() {
    try {
        BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));
        txtName   .setText(readLine(infoReader));
        txtPhone  .setText(readLine(infoReader));
        txtMobile .setText(readLine(infoReader));
        txtAddress.setText(readLine(infoReader));
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(null, ioe.getMessage());
    }
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜