文件较验及Google Gson的使用
一,CRC32文件较验
文件校验可以确保文件内容不被篡改的方法,刚在工作中用到,记录下来。
1 private void doCheckSum(String fileName){ 2 try { 3 4 Log.d("checksum", fileName); 5 6 CheckedInputStream cis = null; 7 long fileSize = 0; 8 try { 9 // Computer CRC32 checksum 10 cis = new CheckedInputStream( 11 new FileInputStream(fileName), new CRC32()); 12 13 fileSize = new File(fileName).length(); 14 15 } catch (FileNotFoundException e) { 16 System.err.println("File not found."); 17 System.exit(1); 18 } 19 20 byte[] buf = new byte[256]; 21 while(cis.read(buf) >= 0) { 22 23 } 24 25 //----------------------------------------------- 26 27 long checksum = cis.getChecksum().getValue(); 28 showText = checksum + " " + fileSize + " " + fileName; 29 30 System.out.println(showText); 31 Log.d("checksum", showText); 32 mHanler.sendEmptyMessage(1); 33 34 35 } catch (IOException e) { 36 e.printStackTrace(); 37 System.exit(1); 38 } 39 }
Gson对于使用JSON数据来说是相当方便的,示例
1 public class WechatConfig { 2 private int Id; 3 4 public int getId() { 5 return Id; 6 } 7 public void setId(int Id) { 8 this.Id = Id; 9 } 10 11 12 13 }
1 WeChat wc = new WeChat(); 2 wc.setId(20); 3 4 String json = mGson.toJson(wc ); 5 6 {"Id":20}
参考:http://www.oschina.net/code/snippet_12_257
http://www.cnblogs.com/haippy/archive/2012/05/20/2509329.html