2012-04-03 77 views
0
public class GenericWorldLoader implements WorldLoader { 
    @Override 
    public LoginResult checkLogin(PlayerDetails pd) { 
     Player player = null; 
     int code = 2; 
     File f = new File("data/savedGames/" + NameUtils.formatNameForProtocol(pd.getName()) + ".dat.gz"); 
     if(f.exists()) { 
      try { 
       InputStream is = new GZIPInputStream(new FileInputStream(f)); 
       String name = Streams.readRS2String(is); 
       String pass = Streams.readRS2String(is); 
       if(!name.equals(NameUtils.formatName(pd.getName()))) { 
        code = 3; 
       } 
       if(!pass.equals(pd.getPassword())) { 
        code = 3; 
       } 
      } catch(IOException ex) { 
       code = 11; 
      } 
     } 
     if(code == 2) { 
      player = new Player(pd); 
     } 
     return new LoginResult(code, player); 
    } 

    @Override 
    public boolean savePlayer(Player player) { 
     try { 
      OutputStream os = new GZIPOutputStream(new FileOutputStream("data/savedGames/" + NameUtils.formatNameForProtocol(player.getName()) + ".dat.gz")); 
      IoBuffer buf = IoBuffer.allocate(1024); 
      buf.setAutoExpand(true); 
      player.serialize(buf); 
      buf.flip(); 
      byte[] data = new byte[buf.limit()]; 
      buf.get(data); 
      os.write(data); 
      os.flush(); 
      os.close(); 
      return true; 
     } catch(IOException ex) { 
      return false; 
     } 
    } 

    @Override 
    public boolean loadPlayer(Player player) { 
     try { 
      File f = new File("data/savedGames/" + NameUtils.formatNameForProtocol(player.getName()) + ".dat.gz"); 
      InputStream is = new GZIPInputStream(new FileInputStream(f)); 
      IoBuffer buf = IoBuffer.allocate(1024); 
      buf.setAutoExpand(true); 
      while(true) { 
       byte[] temp = new byte[1024]; 
       int read = is.read(temp, 0, temp.length); 
       if(read == -1) { 
        break; 
       } else { 
        buf.put(temp, 0, read); 
       } 
      } 
      buf.flip(); 
      player.deserialize(buf); 
      return true; 
     } catch(IOException ex) { 
      return false; 
     } 
    } 

} 

是的,所以......我的问题是,这似乎在真正复杂和难以阅读的方式(二进制)中保存'某些东西',我宁愿把它作为一个.txt,在容易阅读的格式。如何转换?java代码片段的问题

编辑:我不使用Apache的米娜,所以我应该怎么取代

IoBuffer buf = IoBuffer.allocate(1024); 
buf.setAutoExpand(true);" 

用?

回答

0

checkLogin()显然会检查指定的登录是否存在匹配的数据以及密码是否正确。

savePlayer()方法保存播放器。

loadPlayer()再次加载它。

使用的数据格式是gzipwiki),它被写为serialized数据流。如果你想让它更易读,你可能想重载(或者只是使用它,如果它是好的)toString()Player类的方法并且用player.toString()player.toString()写入新的文本文件。 BufferedWriter缠绕着一个File Writer

String playerName = NameUtils.formatNameForProtocol(player.getName()); 
BufferedWriter writer = new BufferedWriter(new FileWriter(playerName + ".txt")); 
writer.write(player.toString()); 
writer.close();