First, you have to read the text file line by line
// your file
File statText = new File("C:/Users/Wicked Angel/Desktop/customers.txt");
// read file using FileReader class
FileReader fr = new FileReader(statText);
BufferedReader br = new BufferedReader(fr);
// the first line is the header line and might be ignored
String line = br.readLine();
// loop through each line by reading it from the buffer
while ((line = br.readLine()) != null) {
// process each line
}
br.close();
This will loop through each lines in your file. The line
will be a string. Here below is an example of the first string in the while loop.
line: "5487,Samer,Lebanon,1000000"
What you have to do is to separate each parts and bring it to an array. This can be done with the Split()
method from String
-object. (click on the method name to read the documentation).
String[] myParts = line.Split(",");
The result will be then
myParts: ["5487"] ["Samer"] ["Lebanon"] ["1000000"]
That's an array. Just go through the above array and store each variable in the appropriate array. The first element in ArrayList<int> accounts
, the second element in ArrayList<String> names
... Here below is an example for the first element
// outside loop
ArrayList<int> accounts = new ArrayList<int>();
// inside loop
accounts.Add(Integer.parseInt(myParts(0)));
// since it should be an integer, I parse it to int before adding it
The reason behind the use of ArrayList
is because you don't know how many lines you have in your text. Ofc you can check it, but performance wise, it's advisable to use a dynamic array, which is ArrayList
. (Or other list objects if you want). If you want to read more about ArrayList
, please refer to this documentation to create, add element, get element, ...
Oh, also don't forget to cast the first and third element to int, or you will get errors when trying to add these info in an int
ArrayList. If you want, you can also validate each element to ensure that you don't have faulty data (like the result of splitting a line is an array of three elements, which is incorrect).
This should help you to solve your import problems. Good luck