Hi!
Could someone please help me to solve one more problem.
To read the data (ArrayList) from file, I'm using the following code, which assumes that columns are separated with ",". It works perfectly:
public static List<UserDataRow> readData()
{
List<UserDataRow> listofusers = new ArrayList<UserDataRow>();
FileInputStream fstream = null;
try
{
fstream = new FileInputStream("src/filetree/UserDataFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine = "";
String[] tokens = strLine.split(", ");
//Read file line by line
while ((strLine = br.readLine()) != null) {
// Copy the content into the array
tokens = strLine.split(", ");
listofusers.add(new UserDataRow(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]));
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try { fstream.close(); } catch ( Exception ignore ) {}
}
return listofusers;
}
To write the date, I've tried using ObjectOutputStream, which actually assumes different separators. It also works correctly:
public void insertrow(String regNr, String firstName, String lastName, String profession, String sex, String dateofbirth) {
List<UserDataRow> userDataList = filetree.FilterClass.readuserdatafromfile();
UserDataRow ud = new UserDataRow(regNr, firstName, lastName, profession, sex, dateofbirth);
userDataList.add(ud);
try{
FileOutputStream fileOut = new FileOutputStream("src/filetree/UserDataFile.txt");
ObjectOutputStream oos = new ObjectOutputStream (fileOut);
oos.writeObject (userDataList);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
But the problem is these two codes could not be used for the same file, because they assume different data formats. To solve the problem, I've tried using ObjectInputStream for reading the data from file. But I've noticed that the System.out.println(listofusers.size()) = 0. Could someone please explain me why does it happen? What coudl be the best solution for this case? Thanks a lot.
public static List<UserDataRow> readData() {
List<UserDataRow> listofusers = new ArrayList<UserDataRow>();
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream("src/filetree/UserDataFile.txt");
in = new ObjectInputStream(fis);
listofusers = (ArrayList) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
System.out.println(listofusers.size());
return listofusers;
}