我已将数据写入二进制文件。但我不知道如何从二进制文件中读取。对于写入我有帐号,用户名,密码,名称写入二进制文件如下:
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 ();
}
}
}
请有人通过从二进制文件中提供该客户的帐号来帮助我读取该客户的数据。我使用以下代码阅读。但它显示错误。我只想通过提供帐号来显示客户的所有数据。
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 ();
}
}
}
}
“二进制”和“逐行”是相互矛盾的。下定决心。您正在使用writeObject()
,这意味着二进制和序列化,并且您根本不应该编写行终止符。你只需要使用ObjectInputStream.readObject()
来读取这个文件。
你也不需要迭代。只需编写整个集合对象。或者确实是整个Map
,每次都没有附加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句