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

来源:互联网 发布:python snmp 系统监控 编辑:程序博客网 时间:2024/06/05 16:31

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

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

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();}}}

原创粉丝点击