File io流的学习
首先复习了上节课以及讲过的文件的创建,改名以及文件的删除,这些功能的代码如下:
File file1=new File(“C:\Users\asus\Desktop\作业\aaa.txt”);
file1.createNewFile();
System.out.println(file);
File newfile=new File(“C:\Users\asus\Desktop\作业\bbb.txt”);
file1.renameTo(newfile);
newfile.delete();
之后讲的是通过Java对文件进行输入信息或读取信息并将信息打印在Java上,其代码如下:
File a=new File(“C:\Users\asus\Desktop\作业\ddd.txt”);
FileWriter fs= new FileWriter(“C:\Users\asus\Desktop\作业\ddd.txt”);
fs.write(“Hello”);
fs.close();
System.out.println(“写数据成功!”);
FileReader fr=new FileReader(“C:\Users\asus\Desktop\作业\ddd.txt”);
BufferedReader buf=new BufferedReader(fr);
String r=buf.readLine();
System.out.println®;
最后将的是对文件夹内的文件名进行读取并且打印到Java上,其代码如下:
public static void main(String[] args) {
File b= new File(“C:\Users\asus\Desktop\作业”);
String[] list =b.list();
for(String s :list)
{
System.out.println(s);
}
}
Jdbc的简化完善
首先先对开头加载驱动,创建连接和结尾关闭资源的简化,简化方法是新建一个class:DBUtil,在DBUtil放入加载驱动和创建连接所需的代码以及关闭资源所需的代码,其代码如下:
public Connection getConection(){
Connection connection=null ;
try {
Class.forName(“com.mysql.jdbc.Driver”);
connection= DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/2?useSSL=true&characterEncoding=utf-8&user=root&password=123456”
);}catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public void closeAll(ResultSet rs, PreparedStatement preparedStatement, Connection connection)
{
if (rs!=null)
{
try {
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(preparedStatement!=null)
{
try {
preparedStatement.close();
} catch (SQLException e){
e.printStackTrace();
}
}
if(connection!=null)
{
try {
connection.close();
} catch (SQLException e){
e.printStackTrace();
}
}
return ;
}
以后在Jdbc增删改查功能代码中进行的调用,调用方法如下:
开头:
DBUtil dbUtil=null;
dbUtil =new DBUtil();
connection=dbUtil.getConection();
结尾:
dbUtil.closeAll(resultSet,preparedStatement,connection);
之后还有对查询的一个优化,就是将查询的内容存在List里,代码如下:
public class Student {
private int id;
private String name;
private String pssword;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPssword() {
return pssword;
}
public void setPssword(String pssword) {
this.pssword = pssword;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", pssword='" + pssword + '\'' +
'}';
}
再再查询程序中调用:
List<Student>students=new ArrayList<>();
while (resultSet.next()){
Student student=new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setPssword(resultSet.getString(3));
students.add(student);
}
System.out.println(students);