I have written the data into binary file.But i dont know how to read from binary file. For writing i have account number, username ,password, name to write into binary file as below:
LinkedHashMap<String, String> details = new LinkedHashMap<String, String>();
details.put("Acount Number", "1986940573948");
details.put("Username", "Krischal");
details.put("Password", "8749578679");
details.put("Name","Krischal mahat");
String filename="dataFiles\\Customers.dat";
addCustomer (filename, details.values(), true);
public static void addCustomer (String filename, Collection col, boolean append){
File file = new File (filename);
ObjectOutputStream out = null;
String str;
try{
if (!file.exists () || !append) out = new ObjectOutputStream (new FileOutputStream (filename));
else out = new AppendableObjectOutputStream (new FileOutputStream (filename, append));
Iterator itr = col.iterator();
while (itr.hasNext()) {
str = (String) itr.next();
out.writeObject(str);
}
out.writeObject("\n");
out.flush ();
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (out != null) out.close ();
}catch (Exception e){
e.printStackTrace ();
}
}
}
Please someone help me to read data of customer by giving the account number of that customer from binary file. Ihave used following code to read .But its showing errors. I just want to display all data of customer by providing account number.
public static void check (String filename){
File file = new File (filename);
if (file.exists ()){
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream (new FileInputStream (filename));
while (true){
String s = (String)ois.readObject ();
System.out.println (s);
}
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
'Binary' and 'line by line' are mutually contradictory. Make up your mind. You're using writeObject(), which means binary, and Serialization, and you shouldn't be writing line terminators at all. You just need to use ObjectInputStream.readObject() to read this file.
You don't need to iterate, either. Just write the whole collection object. Or indeed the entire Map, every time, without appending.