20个非常有用的java片段(上)

本文转至软件开发学习资讯

内容比较早,有些函数过时了,但是总体思路是不错的。

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) {
			e.printStackTrace();
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

3得到当前方法的名字

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

4转字符串到日期

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

或者

                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 conn;
	
	public void init(FileInputStream fs) throws IOException, ClassNotFoundException, SQLException {
		Properties props = new Properties();
		props.load(fs);
		String url = props.getProperty("db.url");
		String userName = props.getProperty("db.userName");
		String passWord = props.getProperty("db.passWord");
		Class.forName(driverClass);
		conn = DriverManager.getConnection(url, userName, passWord);
	}
	
	public void fetch() throws SQLException {
		PreparedStatement ps = conn.prepareStatement("select sysdate from dual");
		ResultSet rs = ps.executeQuery();
		while(rs.next()) {
			//do the thing you do
		}
		rs.close();
		ps.close();
	}
	
}

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使用NIO进行快速的文件拷贝

public static void fileCopy(File in, File out) throws IOException {
		
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();
		try {
			int maxCount = (64*1024*1024) - (32*1024);
			long size = inChannel.size();
			long position = 0;
			while(position < size) {
				position += inChannel.transferTo(position, maxCount, outChannel);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if(inChannel != null) {
				inChannel.close();
			}
			if(outChannel != null) {
				outChannel.close();
			}
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值