您的位置:首页 > 职场人生

面试常考的三个手写代码

2016-09-25 19:32 176 查看
1.NO.1 设计一个类只能产生一个对对象。(可以采用23中设计模式中的单利模式)

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

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 面试