最后修改:2016-01-28 16:23

1、 字符串有整型的相互转换

String a = String.valueOf(2); 
int i = Integer.parseInt(a); 

2、 向文件末尾添加内容

BufferedWriter out = null;
try {
    out = new BufferedWriter(new FileWriter("filename", true));
    out.write("aString");
} catch (IOException e) {
    // error processing code 
} finally {
    if (out != null) {
        out.close();
    }
}

3、 得到当前方法的名字

String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

4、 字符串转日期

(1)把今天的日期转存字符串

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datestr = sdf.format(new Date());
SimpleDateFormat可接受的参数还有一年中的第D天,一年中的第W周,一个月中第w周,一天中k时,时区z,毫秒值SSS
保存时间到数据库时可以使用yyyyMMddHHmmssSSS

(2)

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

(3)

SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date date = format.parse(myString);

5、 使用JDBC链接Oracle

public class OracleJdbcTest {
    String driverClass = "oracle.jdbc.driver.OracleDriver";

    Connection con;

    public void init(FileInputStream fs) throws Exception {
        Properties props = new Properties();
        props.load(fs);
        String url = props.getProperty("db.url");
        String userName = props.getProperty("db.user");
        String password = props.getProperty("db.password");
        Class.forName(driverClass);

        con = DriverManager.getConnection(url, userName, password);
    }

    public void fetch() throws SQLException, IOException {
        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            // do the thing you do 
        }
        rs.close();
        ps.close();
    }

    public static void main(String[] args) {
        OracleJdbcTest test = new OracleJdbcTest();
        test.init();
        test.fetch();
    }
}

6、 把Java util.Date 转成 sql.Date

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

7、 遍历HashMap的最佳方法

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove();
    }
}

8、产生指定区间内的随机整数

import java.util.Random;
 
public static int randInt(int min, int max) {
 
    Random rand;
    int randomNum = rand.nextInt((max - min) + 1) + min;
 
    return randomNum;
}

9、 创建JSON格式的数据

请先阅读这个文档:

并下载这个jar文件 json - rpc - 1.0.jar(75 kb)

import org.json.JSONObject;

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

String output = json.toString();

10、 正则表达式的一般使用方式

[2015]
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String reg = "^[0-9]+(.[0-9]{2})?$";//只能输入有两位小数的正实数
Pattern pa = Pattern.comple(reg);
Matcher ma = pa.matcher(String string);
if(ma.find()){
    System.out.println(ma.group());
}

11、 HTTP代理设置

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

12、 单实例Singleton示例

public class SimpleSingleton {
    private static SimpleSingleton singleInstance = new SimpleSingleton();
    //Marking default constructor private 
    //to avoid direct instantiation. 
    private SimpleSingleton() {}
    //Get instance for class SimpleSingleton 
    public static SimpleSingleton getInstance() {
        return singleInstance;
    }
}

另一种实现

public enum SimpleSingleton {
    INSTANCE;
    public void doSomething() {}
}

//Call the method from Singleton: 
SimpleSingleton.INSTANCE.doSomething();

13、Java按行读取文件

    InputStream is = new FileInputStream(filePath);
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = br.readLine();
    while (line != null) {
        sb.append(line + "\n"); 
        line = br.readLine();
    }
    sb.toString();
    br.close();
    is.close();

14、 列出文件和目录

File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
    // Either dir does not exist or is not a directory 
} else {
    for (int i = 0; i < children.length; i++) {
        // Get filename of file or directory 
        String filename = children[i];
    }
}
// It is also possible to filter the list of returned files. 
// This example does not return any files that start with `.'. 
FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return !name.startsWith(".");
    }
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects 
File[] files = dir.listFiles();
// This filter only returns directories 
FileFilter fileFilter = new FileFilter() {
    public boolean accept(File file) {
        return file.isDirectory();
    }
};
files = dir.listFiles(fileFilter);

15、获取当前时间的时间戳

    imort java.util.Date;
    long s = new Date().getTime();  

17、 把Array转换成 Map

import java.util.Map;
import org.apache.commons.lang.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        String[][] countries = {
            {
                "United States", "New York"
            }, {
                "United Kingdom", "London"
            }, {
                "Netherland", "Amsterdam"
            }, {
                "Japan", "Tokyo"
            }, {
                "France", "Paris"
            }
        };

        Map countryCapitals = ArrayUtils.toMap(countries);

        System.out.println("Capital of Japan is"+countryCapitals.get("Japan"));
        System.out.println("Capital of France is"+countryCapitals.get("France"));
    }
}

18、 发送邮件

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public void postMail(String recipients[], String subject, String message, String from) 
                    throws MessagingException {
    boolean debug = false;

    //Set the host smtp address 
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.example.com");

    // create some properties and get the default Session 
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message 
    Message msg = new MimeMessage(session);

    // set the from and to address 
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Optional : You can also set your custom headers in the Email if you Want 
    msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type 
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
}

19、 发送代数据的HTTP请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            URL my_url = new URL("http://zhangguoli.cn");
            BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
            String strTemp = "";
            while (null != (strTemp = br.readLine())) {
                System.out.println(strTemp);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

20、 改变数组的大小

private static Object resizeArray(Object oldArray, int newSize) {
    int oldSize = java.lang.reflect.Array.getLength(oldArray);
    Class elementType = oldArray.getClass().getComponentType();
    Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize);
    int preserveLength = Math.min(oldSize, newSize);
    if (preserveLength > 0)
        System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
    return newArray;
}

// Test routine for resizeArray(). 
public static void main(String[] args) {
    int[] a = {
        1, 2, 3
    };
    a = (int[]) resizeArray(a, 5);
    a[3] = 4;
    a[4] = 5;
    for (int i = 0; i < a.length; i++)
        System.out.println(a[i]);
}

更新:

    2015/10/20 新增第8项,产生指定区间内的随机整数 
    2015/11/5  修改第10项为java下正则表达式的一般使用方式
    2015/11/27 新增第13项,Java按行读取文件 

标签: Java, 转载

添加新评论