我已将数据写入二进制文件。但我不知道如何从二进制文件中读取数据。写作我有帐号,用户名,密码,姓名写入二进制文件如下:
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 ();
}
}
}
}
答案 0 :(得分:0)
&#39;二进制&#39;并且逐行排列&#39;相互矛盾。下定决心。您正在使用writeObject()
,这意味着二进制和序列化,您根本不应该编写行终止符。您只需使用ObjectInputStream.readObject()
来阅读此文件。
你也不需要迭代。只需编写整个集合对象即可。或者确实是整个Map
,每次都没有附加。