java常用代码速查

网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
URL相关
URLConnection使用代理:
URL url = new URL(purl);
SocketAddress add = new InetSocketAddress("110.4.12.170", 83);
Proxy p = new Proxy(Proxy.Type.HTTP, add);
URLConnection turl = url.openConnection(p);
turl.setConnectTimeout(urlTimeout);
turl.setReadTimeout(urlTimeout);
BufferedReader in = new BufferedReader(new InputStreamReader(turl.getInputStream(), charset));

socket相关
创建socket:st = new Socket(HOST, PORT);
构造输入输出流:BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(st
.getOutputStream()));
(读)写数据:bw.write(startConnection);
刷新缓冲区:bw.flush();
关闭缓冲区:bw.close();

servlet:
request.setCharacterEncoding("UTF-8");
String wechatid = request.getParameter("openID");//微信号
Map<String, String[]> tmpMap = request.getParameterMap();
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(errormsg.getBytes("UTF-8"));

网页内容读取URLConnection:
URL url = new URL(purl);
URLConnection turl = url.openConnection();
turl.setConnectTimeout(urlTimeout);
turl.setReadTimeout(urlTimeout);
BufferedReader in = new BufferedReader(new InputStreamReader(
turl.getInputStream()));

while ((line = in.readLine()) != null) {
content += line;
}
in.close();


httpclient文件发送:
Protocol myhttps = new Protocol("https",new MySecureProtocolSocketFactory(),443);
Protocol.registerProtocol("https", myhttps);//https需要
HttpClient httpclient=new HttpClient();

PostMethod filePost = new PostMethod("https://api.ffan.com/zhaofangbao/v1/bosera/upload");

//使用系统提供的默认的恢复策略
//filePost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

String param = "verify=" + URLEncoder.encode("verifytest", "utf-8") + "&type=" + "1";
filePost.setQueryString(param);
String filepath = "D:\\工作文件夹\\工作文档\\filetest.txt";
File targetFile = new File(filepath);
Part parts[] = {new FilePart("file", targetFile) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
//执行PostMethod
int statusCode = httpclient.executeMethod(filePost);
System.out.println("thirdChannel batchFileUpload http status:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "+ filePost.getStatusLine());
}
//读取内容
byte[] responseBody = filePost.getResponseBody();
//处理内容
System.out.println(new String(responseBody,"UTF-8"));
TrustAnyTrustManager.java
MySecureProtocolSocketFactory.java
connect.java

参考文章:
http://blog.csdn.net/noodies/article/details/17240805
http://tc.chinawin.net/it/softwaredev/article-eaa5.html
http://www.91r.net/ask/7684654.html
http://blog.sina.com.cn/s/blog_74cef98a0101pl16.html
http://hougbin.iteye.com/blog/1196063

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
字符串
字符串判断空:if(mdbPath==null||mdbPath.length()<=0)
文件读取:while ((tmpline =(BufferedReader) reader.readLine()) != null) {
字符判断:if ('#' == tmpline.charAt(0)) {
字符串切分:tmps = tmpline.split("=");
缓冲串:StringBuffer sbrecvMsg=new StringBuffer();
添加字符:sbrecvMsg.append((char)c);
转化为普通字符串:recvMsg = sbrecvMsg.toString();
清空串:sbrecvMsg.setLength(0);

正则表达式
pattern编译:this.pattern = Pattern.compile(regexp);
模式匹配:Matcher matcher = pattern.matcher(item);
匹配数据取得:if (matcher.find()) { matcher.group(String);}

JE分词用法:
MMAnalyzer analyzer=new MMAnalyzer();
String text="hello";
anaResult=analyzer.segment(text, " | ");

数字格式化
浮点数格式化方法1:sum=String.format("%.5f", rs.getDouble("sum"));
浮点数格式化方法2:DecimalFormat df1 = new DecimalFormat("####.000");System.out.println(df1.format(1234.56));

String形式输出objcet(反射机制)
public static String objToString(Object object) throws Exception {
if(object==null){
return null;
}
StringBuffer sb=new StringBuffer("objToString Object:"+object.getClass().getName()+"\n");
Field[] fields = object.getClass().getDeclaredFields();

for(Field field : fields){
field.setAccessible(true);
if(field.get(object)==null)continue;
if(field.get(object).getClass().equals(java.util.ArrayList.class)){
ArrayList<BaseFund> baseFundList=(ArrayList<BaseFund> )field.get(object);
sb.append("List Start\n");
for(BaseFund baseFund:baseFundList){
sb.append(objToString(baseFund));
}
sb.append("List End\n");
}else{
sb.append(field.getName().toString()+":"+field.get(object).toString()+"\n");
}
}
return sb.toString();
}

容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
ArrayList:
上转型(损失部分方法):List<*> list=new ArrayList<*>();or Collection<*> c=new ArrayList<*>();
添加元素方法:Collection.addAll();
Arrays.asList(?);//数组或逗号分隔元素转为list对象,此时产生的为不可变数组,不可delete或者add,
Collections.addAll(Collection,?);//数组或逗号分隔元素转为list对象
容器的打印:无需处理,java自动良好视觉打印,对数组([]表示的数组)才需要用Arrays.toString();

List:
是否存在:contians();//会调用equals()
移除:remove();//会调用equals()
反查索引:indexOf();//会调用equals()
切分:subList();
包含(全部存在):contiansAll();
交集:retainAll();
去除:removeAll();
转为数组:Collection.toArray();//Collection表示任意集合子类


哈希表
实体集合:Set s=(Map<String,String>)dbconf.entrySet();
常用方法:
map.put("","")
map.remove("")
map.clear()
map.get("")
迭代输出哈希表
java.util.Iterator it = (Map<?,?>)Map.entrySet().iterator();
while (it.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
entry.getKey()
}
for (Entry<String, String> entry : tmpMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}

Collection排序: Collections.sort()利用匿名内部类排序
//排序,让05,98,T开头的按先后排序
Collections.sort(accountList,new Comparator<FundAccountVO>(){
@Override
public int compare(FundAccountVO arg0,FundAccountVO arg1) {
return arg0.getTAAccountID().compareTo(arg1.getTAAccountID());//从小到大排序
}
});
Collections.sort(al,new Comparator<String>(){
@Override
public int compare(String arg0,String arg1) {
return arg0.compareTo(arg1);
}
});

数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MYSQL 数据库连接更新
连接数据库查询更新
String url = "jdbc:MySQL://127.0.0.1:3306/stock";
url+="?characterEncoding=UTF-8";//为解决插入中文乱码问题添加的参数
String user = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed()){if(DEBUG)System.out.println("成功连接数据库");}
Statement statement = conn.createStatement();
Statement stat = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
int info=stat.executeUpdate(sql);
if(info==1){System.out.println("成功更新id为"+rs.getString("id")+"的条目");
}else{System.out.println("失败更新id为"+rs.getString("id")+"的条目");}
name = rs.getString("title");
//name = new String(name.getBytes("ISO-8859-1"),"GB2312");
System.out.println(rs.getString("date") + "\t" + name);
}
rs.close();
conn.close();

其他

日志

1
2
import org.apache.log4j.Logger;
private static Logger logger=Logger.getLogger(TestSocket.class);

编码格式转换

1
2
3
4
5
6
7
8
9
10
11
import org.apache.xml.security.utils.Base64;
BASE64编码:new sun.misc.BASE64Encoder().encode(tempName.getBytes("UTF-8")));
BASE64解码:new sun.misc.BASE64Decoder().decodeBuffer( str );
新Base64编码:base=new Base64();String afterb=base.encode("niahoaa".getBytes());
新BASE64解码:System.out.println(new String(base.decode(afterb)));
int->string:Integer.toString();
String->int:Integer.parseInt();//返回的是int基本类型
String->Bytes:"".getBytes()
Bytes->String:new String(Bytes[])
float->string:String.valueOf(new Float(1.23));
string->float:float f=Float.valueOf("123");//返回的是封装对象,注意使用==判断时问题

随机数获取

1
2
获取随机数对象:Random rd = new Random();
随机整数(有范围限制):System.out.println(rd.nextInt(100));

日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
获得calendar对象:Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。 
格式化时间输出:format = new java.text.SimpleDateFormat("yyyy-MM-dd");
format.format(Calendar.getInstance().getTime());
获取时间戳: 消耗时间从小到大
long t=System.currentTimeMillis();
new Date().getTime();
Calendar.getInstance().getTimeInMillis();
获取日期:
java.util.Calendar c=java.util.Calendar.getInstance();
cal.add(Calendar.DATE,-1);
// 获得今天是一周的第几天,星期日是第一天,星期二是第二天......
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因为按中国礼拜一作为第一天所以这里减1
return(new java.text.SimpleDateFormat("yyyyMMddhhmmss").format(c.getTime()));


日期判断前后:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date end = sdf.parse("2014-06-03 00:00:00");
Date nowDate = new Date();

浮点数格式

1
2
浮点数格式对象:NumberFormat formatter = new DecimalFormat("###,###,##0.00");
System.out.println(formatter.format(0.00));

多线程

1
2
3
创建:Thread sendThd=new Thread(new SendMessage("guozq001",bw));
启动:sendThd.start();
强制次序:sendThd.join();

DOM4JXML解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
读取string获取document:Document document= DocumentHelper.parseText(xmlText);
document获取root元素:Element ele=document.getRootElement();
获取所有子元素:List<Element> childList=element.elements();
获取某节点的单个子节点:Element memberElm=root.element("member");// "member"是节点名
获取元素名称:child.getName()
获取元素值:value=child.getStringValue();
取得节点的文字:String text=memberElm.getText();
取得根节点下的name字节点的文字:String text=root.elementText("name");

取得某节点下指定名称的所有节点并进行遍历.
List nodes = rootElm.elements("member");
for (Iterator it = nodes.iterator(); it.hasNext();) {
Element elm = (Element) it.next(); // do something
}
对某节点下的所有子节点进行遍历.
for(Iterator it=root.elementIterator();it.hasNext();){
Element element = (Element) it.next(); // do something
}

创建document:Document doc = DocumentHelper.createDocument();
设置xml编码:doc.setXMLEncoding("GBK");
创建根元素:Element root = doc.addElement("XML");
创建子元素:Element child=root.addElement("ToUserId");
删除某节点:parentElm.remove(childElm); // childElm是待删除的节点,parentElm是其父节点
为元素添加cdata值:child.addCDATA(bizContentMap.get("FromUserId"));
设置节点文字:ageElm.setText("29");
为元素添加text普通值:child.addText(String.valueOf(System.currentTimeMillis()));
创建元素转为XML格式字符串:String responseXML=root.asXML();

W3CDOM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
创建document对象:DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.newDocument();
创建element元素:Element ele = document.createElement("qryInvestorInfoByCustno");
设置元素属性:ele.setAttribute("TransactionAccountID", custno);
添加子元素:document.appendChild(ele);
//从用户个人信息中解析出证件类型和证件号码
获取子元素:Element transAcctElement=(Element)transAcctDocument.getDocumentElement().getFirstChild();
获取元素属性: idtp=transAcctElement.getAttribute("CertificateType");
导入外部元素:Node firstDocImportedNode = retDoc.importNode(transAcctDocument.getDocumentElement(), true);
returnRoot.appendChild(firstDocImportedNode );
节点遍历:
NodeList nodes = reqRoot.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
// 节点名称一定不为空
if (nodes.item(i) == null || nodes.item(i).getNodeName() == null
|| nodes.item(i).getNodeName().trim().length() == 0) {
continue;
}
logger.debug("node:"+nodes.item(i).getNodeName().toLowerCase()+","+nodes
.item(i).getChildNodes().item(0).getNodeValue()+","+nodes
.item(i).getTextContent());
//注意:获得node的value可以使用
//1,nodes.item(i).getChildNodes().item(0).getNodeValue(),当节点内容为空时,依然会报错
//2,nodes.item(i).getTextContent(),相对保险的方法
//不能使用:nodes.item(i).getNodeValue(),这个一般会返回null,诡异的w3cdom反人类啊
}
其他节点遍历方式:
Node node=reqRoot.getFirstChild();
while(node!=null){
/**********/
node=node.getNextSibling();
}

json解析(org.json)

1
2
3
4
5
6
7
初始化JSONObject 方法一:JSONObject jsonObject1 = new JSONObject();jsonObject1.put("Name", "Tom"); 
初始化JSONObject 方法二:JSONObject jsonObject2 = new JSONObject("{'Name':'Tom','age':'11'}");
初始化JSONArray 方法一:JSONArray jsonArray1 = new JSONArray(); jsonArray1.put("abc");
初始化JSONArray 方法二: JSONArray jsonArray2 = new JSONArray("['abc','xyz']");
输出JsonObject(Array类似):jsonObject1.toString());
解析字符串:jsonObject1.getString("Name")(此时name元素对应的value是字符串)
解析对象:jsonObject2.getJSONObject("jsonObject").toString()(此时"jsonObject"对应的value是对象,可用toString()将其显示)

java对象持久化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("d:/tmp.obj")));
oos.writeObject(new Test2());
oos.writeObject(t);
oos.close();

ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("d:/tmp.obj")));
t=(Test2)ois.readObject();System.out.println(t.a+" "+t.b);
t=(Test2)ois.readObject();System.out.println(t.a+" "+t.b);
ois.close();

class Test2 implements Serializable{
public int a;
transient public int b;
public Test2(){
this.a=0;
this.b=1;
}
}

文件读写

1
2
3
4
5
6
7
读:
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((fileLine = br.readLine()) != null) line += fileLine;

BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("");
br.close();

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×