2

I have the following Java class, which I'm using to read a .data file:

import java.io.*;
import java.util.Scanner;

public class ReadFile {
static File file;
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
String filename = "D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data";

public ReadFile(File f) throws FileNotFoundException {
    // TODO Auto-generated constructor stub
    try{
        //File = new File("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data");
        f = new File("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\src\\Person.data");
        Scanner scanner = new Scanner(f);
        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }
    scanner.close();
    }
    finally{

    }
}

public void read(File file2) throws IOException{
    FileReader fr = new FileReader("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\src\\Person.data");
    BufferedReader br = new BufferedReader(fr);
    String line;

    int i = 0;
    while((line = br.readLine())!= null){
        data[i] = line;
        System.out.println(data[i]);
        i++;
    }
    br.close();

    String[] dataNew = new String[i];
    System.arraycopy(data, 0, dataNew, 0, i);
    data = dataNew;
    System.out.println("Data length: " + data.length);
}
}

To give you a more complete understanding of my code, I also have the following Java class, which contains my main method:

import java.io.*;

public class Person {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    ReadFile rf = new ReadFile(f);
    rf.read(ReadFile.file);

}
static File f;
public String id;
public String lastName;
public String firstName;
public String street;
public String city;

public void readPerson() throws FileNotFoundException{
    //File f = new File("Smart Stream Associate Software Engineer (Java) - Bristol/assessment/src/Person.java");
    //InputStream IS = new FileInputStream(f);
}

}

Currently, when I run my program, the console displays two lines that say, "Person.data...." and give the filepath of the .data file that is being read, which will have come from the lines System.out.println(scanner.nextLine()); and System.out.println(data[i]); in my ReadFile.java class, as well as the line "Data length: 1", which will have come from the line System.out.println("Data length: " + data.length); at the end of the class.

I assume that this means that the program has read the first two lines of the .data file, but only stored the first.

What I want to happen, is for it to read the first line, store that in a String, then divide the String up into separate Strings wherever a 'space' appears, and store each of those Strings in an element of the array of Strings that I created at the start of the class- by using the line:

String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};

The separate Strings should be stored to each one in that order- so the first String (before the first space in the original String) would be stored in "personID", the second (after the first space, before the second) would be stored in "lastName", etc.

What I then want to do, is read each of the next lines in the file in turn, storing the elements from each line into the next 'row' of my 'columns' String array (basically creating a table of data, using an array of arrays) whereby the first element of each array is a "personID", the second is a "lastName", etc.

I want to do this until I reach the end of the file, and then print the contents of a couple of elements of the 'columns' array, just to show that it has worked.

I'm not sure how I would go about this, and was just wondering if anyone could point me in the right direction?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Noble-Surfer
  • 3,052
  • 11
  • 73
  • 118
  • 1
    To start with, *don't* store the lines as arrays of arrays. Instead, create a class `Person` with fields like `id`, `lastName`, and so on, and read the lines into `Person` objects. It's also probably better to use a `List` than an array, since a `List` will take care of keeping track of the size for you. – chrylis -cautiouslyoptimistic- Sep 25 '13 at 12:04
  • I have created the Person class- it's the second block ofcode in my question... what I want to know is how to store each line of data read from the file as a new Person object...? – Noble-Surfer Sep 25 '13 at 15:03
  • You'll want to create a `List list = new ArrayList<>();`, and then in your loop, use each line to create a new `Person` object and add it to the list. You could do this by parsing each line and passing the arguments to the `Person` constructor as Java arguments. – chrylis -cautiouslyoptimistic- Sep 25 '13 at 15:05
  • Thanks- that sounds like it's exactly what I want, so I've tried adding the line `Person p = new Person("personID", "lastName", "firstName", "street", "city" );` to my while loop, but it's giving me an error that says: "The constructor Person(String, String, String, String, String) is undefined"... If I try changing my 'Person' class, so that I have `public class Person(String, String, String, String, String) {` as the first line, instead of just `public class Person(){` which is what I had previously, then I get a few errors on that line saying: – Noble-Surfer Sep 25 '13 at 16:31
  • "(" implements expected, insert "}" to complete block, and syntax error on token ")", { expected... any ideas why this is? If I leave the line as `public class Person(){`, I have errors that say: Syntax error on token "class", @ expected, and Syntax error, insert "}" to complete block. Do you know what I can do to resolve these problems? – Noble-Surfer Sep 25 '13 at 16:33
  • I'm away from my computer, so I can't look it up for you now, but search for a tutorial on Java constructors. – chrylis -cautiouslyoptimistic- Sep 25 '13 at 23:05

1 Answers1

1
final Scanner in = new Scanner(new FileReader("filename.txt"));
    final List<Person> persons= new ArrayList<Person>();
    while (in.hasNext()) {
        final String[] columns = in.next().split(" ");
                    final Person person = new Person();
                    Person.setId(column[0]);
                    Person.setName(column[1]);
                    // like this you can set all the fields     
        persons.add(person);
    }

You can then loop through few records from the columns list and display the same

As suggested in comment according to OOPS the best design would be to have a person object and storing the data from file as list of Person objects

Pratik Shelar
  • 3,154
  • 7
  • 31
  • 51
  • Hey, thanks for your answer- as I've commented in reply to the comment, I have created the Person class- it's the second block of code in my question... what I want to know is how to store each line of data read from the file as a new Person object...? I think I've confused myself a bit by saying "array of arrays"- it's been a few years since I last did any programming Java... would the code you suggested above enable me to store each line of data a separate Person object? – Noble-Surfer Sep 25 '13 at 15:08
  • Thanks for the updated code- however, I see that your code is to read data from a .txt file... I want to read from a .data file... does this make a difference, or does it work the same just with "filename.data" rather than "filename.txt"? – Noble-Surfer Sep 26 '13 at 11:49
  • I've tried adding the code you've suggested, and I'm getting a couple of compile errors: in the lines `Person.setID(column[0]); Person.setName(column[1]);` it's telling me that 'column' cannot be resolved to a variable- should this be 'columns', as that's what my String array is called? Also, I'm told that I need to insert "Finally" to complete block statements? Where would I insert this? – Noble-Surfer Sep 26 '13 at 11:58
  • Ok, cheers. So presumably then, I need to add set methods for setID and setName in my Person class? – Noble-Surfer Sep 26 '13 at 12:19
  • Yes you need to have setters and getter in your Person class for each field which will allow you to access the fields. This is encapsulation. – Pratik Shelar Sep 26 '13 at 16:27