有用的Java代码片段
下面是20个非常有用的Java程序片段,希望能对你有用。
1. 字符串有整型的相互转换
Java代码
String a = String.valueOf(2); 或者 String a=2+""; //integer to numeric string
int i = Integer.parseInt(a); //numeric string to an int
2. 向文件末尾添加内容
Java代码
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. 得到当前方法的名字
Java代码
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
4. 转字符串到日期
Java代码
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
或者是:
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );
5. 使用JDBC链接Oracle
Java代码
public class OracleJdbcTest
{
String driverClass = "oracle.jdbc.driver.OracleDriver";
Connection con;
public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
{
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();
相关文档:
下面的程序被设计用来打印它的类文件的名称。如果你不熟悉类字面常量,那么我告诉你Me.class.getName()将返回Me类完整的名称,即“com.javapuzzlers.Me”。那么,这个程序会打印出什么呢?
package com.javapuzzlers;
public class Me {
public static void main(String[] args){
System.out.pr ......
下面的程序将打印一个单词,其第一个字母是由一个随机数生成器来选择的。请描述该程序的行为:
import java.util.Random;
public class Rhymes {
private static Random rnd = new Random();
public static void main(String[] args) {
StringBuffer word = null;
switch(rnd.nextInt(2)) {
......
下面的程序循环遍历byte数值,以查找某个特定值。这个程序会打印出什么呢?
public class BigDelight {
public static void main(String[] args) {
for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
if (b == 0x90)
System.out.print("Joy!");
}
......
下面的程序计算了一个循环的迭代次数,并且在该循环终止时将这个计数值打印了出来。那么,它打印的是什么呢?
public class InTheLoop {
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 100;
public static void main(String[] args) {
int count = 0 ......
下面的谜题以及随后的五个谜题对你来说是扭转了局面,它们不是向你展示某些代码,然后询问你这些代码将做些什么,它们要让你去写代码,但是数量会很少。这些谜题被称为“循环者(looper)”。你眼前会展示出一个循环,它看起来应该很快就终止的,而你的任务就是写一个变量声明,在将它作用于该循环之上时,使得该 ......