面试常考的三个手写代码
2016-09-25 19:32
176 查看
1.NO.1 设计一个类只能产生一个对对象。(可以采用23中设计模式中的单利模式)
2.NO.2 java连接数据库
3.NO.3 I/O操作中copy文件
<span style="font-size:14px;">public class Singleton{ private static Singleton s; private Singleton(){ } public static Singleton getInstance(){ if(s == null){ synchronized(Singleton.class){ if(s == null){ s = new Singleton(); } } } return s; } }</span>
2.NO.2 java连接数据库
<span style="font-size:12px;">public class ConnectToDB { public static void main(String[] args) { //1、加载驱动---JDK1.8可以省略这个代码 try { Class.forName("com.mysql.jdbc.Driver");//反射代码---类加载 } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //2、获取连接 Connection con = null; String url = "jdbc:mysql://localhost:3306/test129?useSSL=true&useUnicode=true&characterEncoding=utf8";//协议://ip地址:端口号/数据库名 String username = "root"; String password = "root"; try { con = DriverManager.getConnection(url,username,password); //3、构建语句对象 String sql = "insert into t_group(f_groupName,f_groupAddress,f_groupNum) " + "values('H组','戛纳',4)"; Statement state = con.createStatement();//通过连接获取语句对象 //4、语句对象执行SQL int r = state.executeUpdate(sql);//所有的DML语句都调用这个方法,该方法默认返回影响了多少行 /* * 新增数据时,有时候会需要得到自动生成的主键值. int r = state.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = state.getGeneratedKeys(); if(rs.next()){ int id = rs.getInt(1); System.out.println(id); } */ } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ //5、关闭连接 if(con != null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }</span><span style="font-size: 14px;"> </span>
3.NO.3 I/O操作中copy文件
public class CopyFiles { public static void main(String[] args) { FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream("D:/360Downloads/Adobe AIR_3.2.0.2070.exe"); fout = new FileOutputStream("E:/j129.exe"); byte[] buffer = new byte[1024]; int length = 0;//记录每次读了多少个字节,关键是记录最后一次 while((length = fin.read(buffer)) != -1){ fout.write(buffer, 0, length); fout.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(fin != null){ try { fin.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fout != null){ try { fout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
相关文章推荐
- 面试常考手写代码之--二叉树层次遍历(BFS)
- 面试常考手写代码之--二叉树层次遍历(BFS)
- 判断一个点是否在三个点组成的三角形内 java 代码 面试经典
- C++面试基础之手写代码
- Java面试手写代码No.3(Singleton)
- Java面试手写代码No.1(JDBC)
- 技术面试手写代码考题--二分查找
- 归并排序 笔试面试手写代码常考
- 面试手写代码题目
- 今日头条面试手写代码-找出所有非递增减的子数组
- 华为面试 手写代码 判断int类型的数是否是回文
- 面试手写代码的题目
- 面试常考手写代码之--二叉树非递归遍历
- 归并排序 笔试面试手写代码常考
- 技术面试常被用来作为手写代码的考题汇总
- repeater的手写代码绑定,实现分页和嵌套
- [导入]小菜编程成长记(一 面试受挫——代码无错就是好?)
- 收集的Asp.Net面试程序代码
- 提高Java代码可重用性的三个措施
- datalist的手写代码更新记录