有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从二进制文件读取

我已将数据写入二进制文件。但我不知道如何读取二进制文件。对于写入,我有帐号、用户名、密码、名称,要写入二进制文件,如下所示:

  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 ();
              }
          }
      }
  }

共 (1) 个答案

  1. # 1 楼答案

    “二进制”和“逐行”是相互矛盾的。下定决心吧。您正在使用writeObject(),这意味着二进制和序列化,您根本不应该编写行终止符。你只需要使用ObjectInputStream.readObject()来读取这个文件

    你也不需要迭代。只需编写整个集合对象。或者实际上是整个Map,每次都没有附加