So i have this dat file (txt file) that has one state and one zipcode each of a country. In this dat file i have a semi semicolon that separates the strings for each line and the integers for each line. I am also using an interface and a main class for this but this is the class that should do most of the work. And down below is the method.
PS: I have tried to find other questions on this site that already answers my Q but non of them actually helped!
This is what the dat file has :
75242;Uppsala
90325;Umeå
96133;Boden
23642;Höllviken
35243;Växjö
51000;Jönköping
72211;Västerås
My problem is that i cannot find a way to keep the integers or the strings in the arrays in the way that i want them to work. Have tried to read only integers and only strings but that didn't work. Do also note that i have tried to read every line and then every char in the dat file to try to put the values in their own arrays. Also tried to shift them by using if'ments and saying "if(Character.is..)". In the method below i'm only trying to capture the integers.
Was also thinking that due to the semicolon i should use something like "Character.is...." to check for that and then go over from reading ch/string to int. But want to take one step at the time or else i won't get anything done!
public void read() {
try {
ArrayList<Integer> itemArr = new ArrayList<Integer>();
ArrayList<String> descArr = new ArrayList<String>();
FileReader file = new FileReader("C:\\Users\\me\\Desktop\\places.dat");
BufferedReader r = new BufferedReader(file);
int r1;
while ((r.readLine()) != null) {
while ((r1 = r.read()) != -1) {
char ch = (char) r1;
if (Character.isDigit(ch)) {
itemArr.add(r.read());
}
}
}
} catch (IOException e) {
}
}
This is what is expected : They are also sorted, but i can handle that as long as i can figure out of how to store the correctly in each of their own arrays.
23642 Höllviken
35243 Växjö
51000 Jönköping
72211 Västerås
75242 Uppsala
90325 Umeå
96133 Boden
Thanks for all the comments, really does help.
You can change your logic to the following :
String currLine;
while ((currLine = r.readLine()) != null) {
if (currLine.trim().length() > 0) {
String[] split = currLine.split(";");
itemArr.add(Integer.parseInt(split[0]));
descArr.add(split[1]);
}
}
Here we split each line(currLine) based on ;
and store it into the array split
. Now the 0th index will contain the number and the 1st index will contain the String.
To add it the the itemArr
you need to parse it to an int
. Also note that if the line is empty it is skipped. Sorting it is also pretty straight-forward now.