tags:

views:

112

answers:

8

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!

+1  A: 

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.

extraneon
i'm getting an error when i put that import line, do i put my program name where it says FileUtils? i really dont understand any of this java malarky! it says system.out.println, how do i get the text to the Jtextfields??thanks
addiosamigo
You'd need the Apache Commons IO JAR file in your classpath to be able to use that import line; it's importing external functionality.
Dean J
You do need to download Apache Fileutils and put it in your classpath.
extraneon
And also look at the other apache modules. They really to make it easier to use Java. A favorite of mine is StringUtils.
extraneon
do i just have to Address.add(iter.next()); or txtAddress??also i'm still getting an error on the import statement.
addiosamigo
how do i put it in my classpath??
addiosamigo
i'm not even sure what to download?
addiosamigo
Commons-IO: http://commons.apache.org/downloads/download_io.cgiPutting it in the classpath depends on the packaging, but I usually put it in a directory 'lib' in the project, F5 (refresh) the project in Eclipse, and right-click on the jars in the lib directory and "Add to classpath". For adding in classpath for stand-alone or web apps check the manifest, or google.
extraneon
A: 

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));
}
monksy
this is like alien language for me! i just dont get it! can you dumb it down for me please thanks
addiosamigo
I mostly describe the stuctures of the two classes.
monksy
A: 
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);
    }
tommaso
A: 

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.

NawaMan
I'd throw the exception in readLine, and make it private. You're only using it in importContacts, and catch the exception there anyway!
extraneon
@extraneon: That is true :-D
NawaMan
+2  A: 

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();
Milhous
A: 

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.

Jorn
A: 

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;
}
Jorn
A: 

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

spork
no its four lines of four at the start but when i add more contacts it will become more. thanks
addiosamigo
Then you're probably better off using BufferedReader.readLine() or Scanner.nextLine() as other users have suggested.
spork