【发布时间】:2017-04-28 17:01:35
【问题描述】:
我已将数据写入二进制文件。但我不知道如何从二进制文件中读取数据。对于写入,我有帐号、用户名、密码、要写入二进制文件的名称,如下所示:
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 ();
}
}
}
}
【问题讨论】:
-
那个文件看起来不像是二进制文件。有什么理由不以 json 或 xml 等通用格式编写/读取它?
标签: java serialization