1.这么拼参数的
学习一下,当keys.length-1是加上"&"而且是在拼串的后面
public static String map2Content(Map params){ StringBuilder stringBuilder=new StringBuilder(); try { Set keySet=params.keySet(); Object[] keys=keySet.toArray(); for (int i=0; i < keys.length; i++) { stringBuilder.append(encode(keys[i].toString(),"UTF-8")).append("=").append(encode(params.get(keys[i]).toString(),"UTF-8")); if (i < (keys.length - 1)) { stringBuilder.append("&"); } } } catch ( Exception e) { throw new HttpException("failed to generate content from map",e); } return stringBuilder.toString(); }
2.如果文件存在就删除,再创建一个新文件
private void saveUsers(Set<String> set,String fileName){ File f=new File(getDataFolder(),fileName); if (f.exists()) { f.delete(); } try { f.createNewFile(); BufferedWriter bWriter=new BufferedWriter(new FileWriter(f)); int count=0; for ( String name : set) { bWriter.write(name + System.getProperty("line.separator")); count++; } ConsoleUtils.printInfo(NAME,"Saved " + count + " users in '"+ fileName+ "'!"); bWriter.flush(); bWriter.close(); } catch ( Exception e) { ConsoleUtils.printException(e,NAME,"Error while saving file '" + fileName + "'!"); } }
3.if(widget instanceof Checkbox){
CheckBox cb = (Checkbox)widget如果是这个的实例,强转成这个类,常用的写法
}
@Override public Set<Activity> ge
tInstitutionActivities(){ Set<Activity> activities=new HashSet<Activity>(); for (int i=0; i < institutionActivities.getWidgetCount(); i++) { Widget widget=institutionActivities.getWidget(i); if (widget instanceof CheckBox) { CheckBox cb=(CheckBox)widget; if (cb.getValue()) { Activity activity=new Activity(); activity.setId(Integer.parseInt(cb.getFormValue())); activity.setName(cb.getText()); activities.add(activity); } } } return activities; }
4.set中添加元素而且不重复
private Object createStringSet(String... strings){ Set<String> stringSet=new HashSet<String>(); for ( String string : strings) { stringSet.add(string); } return stringSet; }
5.异常时可以返回null,为空可以返回null
public static String getSearchEngineQueryString(HttpServletRequest request,String referrer){ String queryString=null; String hostName=null; if (referrer != null) { URL refererURL; try { refererURL=new URL(referrer); } catch ( MalformedURLException e) { return null; } hostName=refererURL.getHost(); queryString=refererURL.getQuery(); if (Strings.isEmpty(queryString)) { return null; } Set<String> keys=seParams.keySet(); for ( String se : keys) { if (hostName.toLowerCase().contains(se)) { queryString=getQueryStringParameter(queryString,seParams.get(se)); } } return queryString; } return null; }
6.用Iterator遍历collection
@SuppressWarnings("rawtypes") public static String toReadableString(Collection collection){ Iterator it=collection.iterator(); StringBuilder strb=new StringBuilder(); while (it.hasNext()) { Object next=it.next(); strb.append(next.toString() + ", "); } if (strb.length() > 2) { strb.delete(strb.length() - 2,strb.length()); } return strb.toString(); }
7.将JSON字符串变成map
public static Map<String,Object> parseJSON(String jsonBody) throws JSONException { Map<String,Object> params=new HashMap<String,Object>(); JSONObject obj=new JSONObject(jsonBody); Iterator it=obj.keys(); while (it.hasNext()) { Object o=it.next(); if (o instanceof String) { String key=(String)o; params.put(key,obj.get(key)); } } return params; }
8.这样往param中设置参数,request.getParameter()
protected void copyParams(HttpParams target){ Iterator iter=parameters.entrySet().iterator(); while (iter.hasNext()) { Map.Entry me=(Map.Entry)iter.next(); if (me.getKey() instanceof String) target.setParameter((String)me.getKey(),me.getValue()); } }
9.jsonnode的遍历
private <T>List<T> deserializeList(JsonNode jsonNode,String postType,Class<T> type){ JsonNode dataNode=jsonNode.get("data"); List<T> posts=new ArrayList<T>(); for (Iterator<JsonNode> iterator=dataNode.iterator(); iterator.hasNext(); ) { posts.add(deserializePost(postType,type,(ObjectNode)iterator.next())); } return posts; }
10.遍历map
public static void writeOneToMany(final OutputStream sink,Map mapping) throws Exception { final StringBuilder out=new StringBuilder(); if (mapping == null) { mapping=new HashMap(); } final Iterator keyIter=mapping.keySet().iterator(); while (keyIter.hasNext()) { final String name=(String)keyIter.next(); out.append(name).append(" "); final Collection points=(Collection)mapping.get(name); final Iterator pointIter=points.iterator(); while (pointIter.hasNext()) { final Point point=(Point)pointIter.next(); out.append(" (").append(point.x).append(",").append(point.y).append(")"); if (pointIter.hasNext()) out.append(" "); } if (keyIter.hasNext()) { out.append("\n"); } } write(out,sink); }
11.Iterator这么写
public List<File> getFileList(){ List<File> list=new ArrayList<File>(); for (Iterator it=iterator(); it.hasNext(); ) { FileResource resource=(FileResource)it.next(); File file=resource.getFile(); list.add(file); } return list; }
12.set.add(元素)set这么添加元素的
private Object createStringSet(String... strings){ Set<String> stringSet=new HashSet<String>(); for ( String string : strings) { stringSet.add(string); } return stringSet; }
13.格式化日期
/** * Creates a Calendar object based off a string with this format <Day name:3 letters>, DD <Month name: 3 letters> YYYY HH:MM:SS +0000 * @param date - The string we are to convert to a calendar date * @return - The calendar date object that this string represents */ public static Calendar makeDate(String date){ Date d=null; Calendar calendar=Calendar.getInstance(); try { SimpleDateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); d=format.parse(date); calendar.setTime(d); } catch ( ParseException e) { e.printStackTrace(); } return calendar; }
14.学习这种日期的返回方式
public Date getDate(){
if (value == null) {
return null;
}
if (value instanceof Date) {
return (Date)value;
}
throw new DbException(String.format("%s is not a date",value.toString()));
}
15.为什么要这么判断呢?
public Date parse(final String source) throws ParseException { if (source == null) { throw new ParseException("source is null",0); } return formater.parse(source); }
16.
public static String getSearchEngineQueryString(HttpServletRequest request,String referrer){ String queryString=null; String hostName=null; if (referrer != null) { URL refererURL; try { refererURL=new URL(referrer); } catch ( MalformedURLException e) { return null; } hostName=refererURL.getHost(); queryString=refererURL.getQuery(); if (Strings.isEmpty(queryString)) { return null; } Set<String> keys=seParams.keySet(); for ( String se : keys) { if (hostName.toLowerCase().contains(se)) { queryString=getQueryStringParameter(queryString,seParams.get(se)); } } return queryString; } return null; }
17.
/** * Gets URL for base of path containing Finalizer.class. */ URL getBaseUrl() throws IOException { String finalizerPath=FINALIZER_CLASS_NAME.replace('.','/') + ".class"; URL finalizerUrl=getClass().getClassLoader().getResource(finalizerPath); if (finalizerUrl == null) { throw new FileNotFoundException(finalizerPath); } String urlString=finalizerUrl.toString(); if (!urlString.endsWith(finalizerPath)) { throw new IOException("Unsupported path style: " + urlString); } urlString=urlString.substring(0,urlString.length() - finalizerPath.length()); return new URL(finalizerUrl,urlString); }
18.catch时可以返回返回值类型的
/** * Reads in data from the saved file. * @param context - Context that gives us some system access * @return - Returns the list of items that were saved; If there was problemwhen gathering this data, an empty list is returned */ @SuppressWarnings("unchecked") public static ArrayList<Article> readData(Context context){ ArrayList<Article> oldList=new ArrayList<Article>(); try { FileInputStream fileStream=context.openFileInput("articles"); ObjectInputStream reader=new ObjectInputStream(fileStream); oldList=(ArrayList<Article>)reader.readObject(); reader.close(); fileStream.close(); return oldList; } catch ( java.io.FileNotFoundException e) { return new ArrayList<Article>(); } catch ( IOException e) { Log.e("AARSS","Problem loading the file. Does it exists?",e); return new ArrayList<Article>(); } catch ( ClassNotFoundException e) { Log.e("AARSS","Problem converting data from file.",e); return new ArrayList<Article>(); } }
19.在finally中关闭输入流
public static void read(Properties props,File file) throws IOException { FileInputStream fis=null; try { fis=new FileInputStream(file); props.load(fis); } finally { close(fis); } }
20.