Jeremiah
Jeremiah

Reputation: 324

Loading elements of Array into a collection

I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.

public static void main(String[] args) {
    String fname = "src\\workshop7\\customers.txt";
    String s;
    String[] Name;
    String[] lastName, firstName;
    String last, first;


    RandomAccessFile f;      

    try {
        f = new RandomAccessFile(fname, "r");
        while ((s = f.readLine()) != null) {                
            Name = s.split("\\s");                                
            System.out.println(Arrays.toString(Name)); 

            for (int i = 0; i < Name.length; i++) {
                first = Name[0];
                last = Name[1]; 

            System.out.println("last Name: " + last + "First Name: "+ first);

            }                
        }
        f.close();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }  


}

Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks

Upvotes: 0

Views: 91

Answers (2)

bhupen
bhupen

Reputation: 470

public static void main(String[] args) throws FileNotFoundException {
    BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
    String str;
    String names[];
    List<String> firstName = new ArrayList();
    List<String> lastName = new ArrayList();
    try {
        while ((str = in.readLine()) != null) {
            names = str.split("\\s");
            int count = 0;
            do{
                firstName.add(names[count]);
                lastName.add(names[count+1]);
                count = count + 2;
            }while(count < names.length);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // do whatever with firstName list here
    System.out.println(firstName);
    // do whatever with LastName list here
    System.out.println(lastName);
}

Upvotes: 1

Michael Queue
Michael Queue

Reputation: 1400

You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java

  public class tmp {
        public static void main(String[] args) throws FileNotFoundException {
            //problem you have to create an array of fixed size
            String[] array = new String[4];
            readLines(array);
        }

        public static String[] readLines(String[] lines) throws FileNotFoundException {
            //this counter can be printed to check the size of your array
            int count = 0; // number of array elements with data

            // Create a File class object linked to the name of the file to read
            java.io.File myFile = new java.io.File("path/to/file.txt");

            // Create a Scanner named infile to read the input stream from the file
            Scanner infile = new Scanner(myFile);

            /* This while loop reads lines of text into an array. it uses a Scanner class
             * boolean function hasNextLine() to see if there another line in the file.
             */

            while (infile.hasNextLine()) {
                // read a line and put it in an array element
                lines[count] = infile.nextLine();
                count++;  // increment the number of array elements with data
            } // end while
            infile.close();
            return lines;
        }
    }

However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.

 public static void main(String[] args) throws IOException {

    BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
    String str;
    ArrayList<String> list = new ArrayList<String>();

    while ((str = in.readLine()) != null) {
        list.add(str);
    }

    String[] stringArr = list.toArray(new String[0]);

A little about random access.

Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.

Upvotes: 2

Related Questions