Some useful java codes

来源:互联网 发布:淘宝助手导出数据包 编辑:程序博客网 时间:2024/06/06 10:47
1. Collections.sort for ArrayList

Collections.sort(urlList,new Comparator<UrlEntity>(){    public int compare(UrlEntity objOne, UrlEntity objTwo) {return ((Double)objTwo.getPr()).compareTo((Double)objOne.getPr());    }});


2. Collections.sort for HashMap

Map<Integer, Integer> map = new HashMap<Integer, Integer>();List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>(){public int compare(Map.Entry<Integer, Integer> one, Map.Entry<Integer, Integer> two){return one.getValue().compareTo(two.getValue());}});


4. Traversal for HashMap

for(Iterator iter = map.entrySet.iterator(); iter.hasNext; ){    Entry entry = (Entry) iter.next();    String key = (String) entry.getKey();    String value = (String) entry.getValue();}


for(String key : map.keySet()){    String value = map.get(key);}


5. Traversal for HashSet

for(Iterator<String> iter = set.iterator(); iter.hasNext(); ){    String key = iter.next();}


for(String key : set){}

6. 单数单词变复数

System.out.println(Inflector.getInstance().pluralize("project")); //打印 projectsSystem.out.println(Inflector.getInstance().pluralize("news")); //打印 newsSystem.out.println(Inflector.getInstance().tableize(BlogComment.class)); //打印 blog_commentsInflector.getInstance().singularize("including Classes");//复数变单数


7. 有效数字

BigDecimal b = new BigDecimal(0.0123, new MathContext(4));
或者

BigDecimal bd = new BigDecimal(0.123456);bd = bd.round(new MathContext(5));

8. Pattern and Matcher

Pattern pattern = Pattern.compile(reg);  String[] lines = entityBody.split("(\n|\r\n)+");  for(int i = 0; i < lines.length; i++){       Matcher matcher = pattern.matcher(lines[i]);       while(matcher.find()){            System.out.println(matcher.group());       }  }


9. IOProcess

/******************** * Copyright (c) 2013 Xiaoshi Zhong * All rights reserved. This program and the accompanying materials are made available * under the terms of the GNU lesser Public License v3 which accompanies this distribution, * and is available at http://www.gnu.org/licenses/lgpl.html *  * Contributors : Xiaoshi Zhong * **********************//** * IO / File Processing*/import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.net.URL;public class IOProcess {/** * According the input destination filename, create a new file or a file to append stream to the last, * and the encoding method, create an output stream----OutputStreamWriter * which can automatic create the new file *  * @param filename : indicates the filename of the file to be create * @param isAppend : indicates whether the file to be create is a new file or just append stream into it. * @param encoding : indicates which encoding the file uses. * @return OutputStreamWriter :  * @throws IOException */public static OutputStreamWriter newWriter(String filename, boolean isAppend, String encoding){File file = new File(filename);OutputStreamWriter output = null;/** * If the file to be created does not exist, if needs to create the file path. */try {if(! file.exists()){int lastIndexOfSlash = filename.lastIndexOf("/");if(lastIndexOfSlash != -1){String pathname = filename.substring(0, lastIndexOfSlash);File path = new File(pathname);if(! path.exists())path.mkdirs();}/** In this case, we need to create a new, empty file */file.createNewFile();}else if(! isAppend){file.delete();/** In this case, we need to create a new, empty file */file.createNewFile();}/** * Create an OutputStreamWriter * */output = new OutputStreamWriter(new FileOutputStream(file,true),encoding);} catch (IOException e) {e.printStackTrace();} finally { }return output;}/** * Set the default isAppend to be "false" */public static OutputStreamWriter newWriter(String filename, String encoding){return newWriter(filename, false, encoding);}/** * Set the default encoding to be "UTF-8" */public static OutputStreamWriter newWriter(String filename, boolean isAppend){return newWriter(filename, isAppend, "UTF-8");}/** * Set the default encoding to be "UTF-8", and default isAppend to be "true" *  * @param filename * @return * @throws IOException */public static OutputStreamWriter newWriter(String filename){return newWriter(filename, false, "UTF-8");}/** * Set the default encoding to be "UTF-8" * */public static OutputStreamWriter newWriter(File file, boolean isAppend){return newWriter(file.toString(), isAppend, "UTF-8");}/** * Set the default encoding to be "UTF-8", and default isAppend to be "true" * */public static OutputStreamWriter newWriter(File file){return newWriter(file.toString(), false, "UTF-8");}/** * Save the content to file with the encoding * */public static boolean saveFile(String filename, String content, String encoding){try {OutputStreamWriter output = newWriter(filename, encoding);output.write(content);output.close();return true;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return false;}public static boolean saveFile(File file, String content, String encoding){return saveFile(file.toString(), content, encoding);}public static boolean saveFile(String filename, String content) {return saveFile(filename, content, "UTF-8");}public static boolean saveFile(File file, String content){return saveFile(file.toString(), content);}/** * Get the file list according to the folder name and store them in an file array. *  * @param folderName * @return : the file array */public static File[] getFiles(String folderName){return new File(folderName).listFiles();}/** * Get the file list according to the folder and store them in an file array *  * @param folder * @return : the file array */public static File[] getFiles(File folder){return folder.listFiles();}/** * Create a new buffered reader according to a file and set the default encoding as "UTF-8" *  * @param file * @return * @throws IOException */public static BufferedReader newReader(File file) {return newReader(file, "UTF-8");}/** * Create a new buffered reader according to filename and set the default encoding as "UTF-8" *  * @param fileName * @return * @throws IOException */public static BufferedReader newReader(String fileName) {return newReader(fileName, "UTF-8");}/** * Create a new buffered reader according to the file and the encoding, the file will be changed * into filename string *  * */public static BufferedReader newReader(File file, String encoding){BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return br;}/** * Create a new buffered reader according to the filename and the encoding * */public static BufferedReader newReader(String fileName, String encoding){BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileName)), encoding));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return br;}/** *  Create a new buffered reader according to an url and set the default encoding as "UTF-8" *  * @param url * @return * @throws IOException */public static BufferedReader newReader(URL url){return newReader(url, "UTF-8");}/** * Create a new buffered reader according to an url and the encoding * */public static BufferedReader newReader(URL url, String encoding){BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(url.openStream(), encoding));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return br;}/** * Check whether the file exists or not according to its filename * */public static boolean isFileExist(String filename){File file = new File(filename);if(file.exists())return true;return false;}/** * Delete a file if the file exists * */public static void deleteFile(String filename){File file = new File(filename);if(file.exists())file.delete();}/** * Check the path and complete it if it is not end with "/" * */public static String checkPath(String path){if(!path.endsWith("/"))path += "/";return path;}}


10. ConnectDB

/****************************************************** * Copyright (c) 2014 Xiaoshi Zhong * All rights reserved. This program and the accompanying materials are made available * under the terms of the GNU lesser Public License v3 which accompanies this distribution, * and is available at http://www.gnu.org/licenses/lgpl.html *  * Contributors : Xiaoshi Zhong * *******************************************/import IOProcess;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class ConnectDB {/** * @param args */private Connection conn;private String HOST;private String PORT;private String DATABASE;private String USERNAME;private String PASSWORD;public ConnectDB(String address, String database, String username, String password){setConnection(address, database, username, password);}public ConnectDB(String host, String port, String database, String username, String password){setConnection(host, port, database, username, password);}private void setConnection(String address, String database, String username, String password){String[] items = address.split(":");String url = null;if(items.length == 1){this.HOST = items[0];this.PORT = "3306";//url = "jdbc:mysql://" + address + ":3306/" + database + "?zeroDateTimeBehavior=convertToNull";url = "jdbc:mariadb://" + address + ":3306/" + database + "?zeroDateTimeBehavior=convertToNull";}else if(items.length == 2){this.HOST = items[0];this.PORT = items[1];//url = "jdbc:mysql://" + IOProcess.checkPath(address) + database + "?zeroDateTimeBehavior=convertToNull";url = "jdbc:mariadb://" + IOProcess.checkPath(address) + database + "?zeroDateTimeBehavior=convertToNull";}this.DATABASE = database;this.USERNAME = username;this.PASSWORD = password;setConnection(url, username, password);}private void setConnection(String host, String port, String database, String username, String password){//String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?zeroDateTimeBehavior=convertToNull";String url = "jdbc:mariadb://" + host + ":" + port + "/" + database + "?zeroDateTimeBehavior=convertToNull";this.HOST = host;this.PORT = port;this.DATABASE = database;this.USERNAME = username;this.PASSWORD = password;setConnection(url, username, password);}private void setConnection(String url, String username, String password){try{//Class.forName("com.mysql.jdbc.Driver");//Class.forName("org.postgresql.Driver");Class.forName("org.mariadb.jdbc.Driver");conn = DriverManager.getConnection(url, username, password);} catch (Exception e){e.printStackTrace();System.out.println("Fail to connect database, please check.");return;} finally {}System.out.println("Successful to connect database.");}/** * SELECT count(*) FROM tablename WHERE conditions; * */public ResultSet executeQuery(String sql){ResultSet rs = null;try{Statement statement = conn.createStatement();rs = statement.executeQuery(sql);} catch (SQLException e){e.printStackTrace();System.out.println(sql);} finally {}return rs;}/** * UPDATE tablename SET firstName='Xiaoshi' WHERE lastname='Zhong'; * */public int executeUpdate(String sql){int n = 0;try{Statement statement = conn.createStatement();n = statement.executeUpdate(sql);statement.close();} catch (SQLException e){e.printStackTrace();System.out.println(sql);} finally {}return n;}/** * INSERT INTO tablename (firstname, ..., lastname) VALUES (firstvalue, ..., lastvalue); * */public int executeInsert(String sql){int n = 0;try{Statement statement = conn.createStatement();n = statement.executeUpdate(sql);statement.close();} catch (SQLException e){e.printStackTrace();System.out.println(sql);} finally {}return n;}/** * INSERT INTO tablename (firstname, ..., lastname) VALUES (firstvalue, ..., lastvalue),..., (firstvalue, ..., lastvalue) * ON DUPLICATE KEY UPDATE firstname=VALUES(firstname), ..., lastname=VALUES(lastname); * */public int executeInsertDuplicate(String sql){int n = 0;try{Statement statement = conn.createStatement();n = statement.executeUpdate(sql);statement.close();} catch (SQLException e){e.printStackTrace();System.out.println(sql);} finally {}return n;}/** * Not recommend using REPLACE function * */public int executeReplace(String sql){int n = 0;try{Statement statement = conn.createStatement();n = statement.executeUpdate(sql);statement.close();} catch (SQLException e){e.printStackTrace();System.out.println(sql);} finally {}return n;}public String getHost(){return HOST;}public String getPort(){return PORT;}public String getDatabase(){return DATABASE;}public String getUsername(){return USERNAME;}public String getPassword(){return PASSWORD;}private void releaseConnection(){try{if(conn != null && !conn.isClosed()){conn.close();System.out.println("Successful to close the database connection.");}} catch (SQLException e){e.printStackTrace();} finally {}}public void release(){releaseConnection();}}


11. HttpProcess

/********************************** * Copyright (c) 2015 Xiaoshi Zhong * All rights reserved. This program and the accompanying materials are made available * under the terms of the GNU lesser Public License v3 which accompanies this distribution, * and is available at http://www.gnu.org/licenses/lgpl.html *  * Contributors : Xiaoshi Zhong * ****************************/import java.net.URI;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class HttpProcess {private static HttpClient httpclient;static {httpclient = new DefaultHttpClient();}public static String httpgetText(String inputUrl){return httpgetText(inputUrl, "UTF8");}public static String httpgetText(String inputUrl, String outputEncoding){try {return httpgetText(new URI(inputUrl), outputEncoding);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return null;}public static String httpgetText(URI inputUrl){return httpgetText(inputUrl, "UTF8");}public static String httpgetText(URI inputUrl, String outputEncoding){HttpGet httpget = new HttpGet();httpget.addHeader("User-Agent", "Mozilla/5.0 Firefox/3.5.9 Chrome/26.0.1410.64");String entityBody = null;try {httpget.setURI(inputUrl);HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();if(entity != null){entityBody = EntityUtils.toString(entity, outputEncoding);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {httpget.abort();}return entityBody;}public static String httppostText(String inputUrl, Map<String, String> nameValues, Map<String, String> headers){return httppostText(inputUrl, nameValues, headers, "UTF8", "UTF8");}public static String httppostText(URI inputUrl, Map<String, String> nameValues, Map<String, String> headers){return httppostText(inputUrl, nameValues, headers, "UTF8", "UTF8");}public static String httppostText(String inputUrl, Map<String, String> nameValues, Map<String, String> headers, String inputEncoding, String outputEncoding){try {return httppostText(new URI(inputUrl), nameValues, headers, inputEncoding, outputEncoding);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }return null;}public static String httppostText(URI inputUrl, Map<String, String> nameValues, Map<String, String> headers, String inputEncoding, String outputEncoding){HttpPost httppost = new HttpPost();List<NameValuePair> nvp = new ArrayList<NameValuePair>();for(String name : nameValues.keySet())nvp.add(new BasicNameValuePair(name, nameValues.get(name)));String entityBody = null;try {httppost.setURI(inputUrl);httppost.setEntity(new UrlEncodedFormEntity(nvp, inputEncoding));for(String name : headers.keySet())httppost.addHeader(name, headers.get(name));HttpResponse response = httpclient.execute(httppost);HttpEntity entity = response.getEntity();if(entity != null)entityBody = EntityUtils.toString(entity, outputEncoding);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {httppost.abort();}return entityBody;}}




原创粉丝点击