易截截图软件、单文件、免安装、纯绿色、仅160KB

有用的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();
  


相关文档:

Java解惑2 20我的类是什么I

下面的程序被设计用来打印它的类文件的名称。如果你不熟悉类字面常量,那么我告诉你Me.class.getName()将返回Me类完整的名称,即“com.javapuzzlers.Me”。那么,这个程序会打印出什么呢?
package com.javapuzzlers;
public class Me {
public static void main(String[] args){
System.out.pr ......

Java解惑2 23不劳无获

下面的程序将打印一个单词,其第一个字母是由一个随机数生成器来选择的。请描述该程序的行为:
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)) {
......

Java解惑3 24尽情享受每一个字节

下面的程序循环遍历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!");
}
......

Java解惑3 26在循环中

下面的程序计算了一个循环的迭代次数,并且在该循环终止时将这个计数值打印了出来。那么,它打印的是什么呢?
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 ......

Java解惑2 28循环者

下面的谜题以及随后的五个谜题对你来说是扭转了局面,它们不是向你展示某些代码,然后询问你这些代码将做些什么,它们要让你去写代码,但是数量会很少。这些谜题被称为“循环者(looper)”。你眼前会展示出一个循环,它看起来应该很快就终止的,而你的任务就是写一个变量声明,在将它作用于该循环之上时,使得该 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号