标题java日记
day 7
创建文件aaa.txt
public static void main(String[] args) throws IOException {
File file=new File(“D:\360安全浏览器下载\aaa.txt”);
file.createNewFile();
.重命名bbb.txt
File file1=new File(“D:\360安全浏览器下载\bbb.txt”);
file.renameTo(file1);
删除bbb.txt
file = new File(“D:\360安全浏览器下载\bbb.txt”);
if(file.exists()){
file.delete();
System.out.println(“文件已删除”);
}else
{
System.out.println(“你要删除的文件不存在”); }
在a文件下有 ccc.txt ddd.txt eee.txt 通过java代码把a文件夹下的文件名打印出来
FileReader fr=new FileReader(“D:\\360安全浏览器下载\\aaa.txt”);
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
System.out.println(s);
或者
private static void fileNameList(File[] file)
{
if(file == null)return;
for(File file1 : file)
{
if(file1.isDirectory())
{
fileNameList(file1.listFiles());
}
else
{
System.out.println(file1.getName());
}
}
}
}
在aaa.txt写上 hello 我好开心,作业很少
FileWriter fs=new FileWriter(“D:\360安全浏览器下载\aaa.txt”);
fs.write(“hello 我好开心,作业很少”);
fs.close();
或者
package Test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入要输入的字符”);
String str=sc.next();
System.out.println(“你输入的字符为”);
System.out.println(str);
try {
BufferedWriter buff = new BufferedWriter(new FileWriter(“D:\360安全浏览器下载\aaa.txt”));
buff.write(str);
buff.flush();
buff.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
jabc的删除
因为开头和结尾有很多地方相同,为避免多次出现,我们新建一个包,在建一个DBUtil用来存放相同的内容,到时候直接引用就好了
import java.sql.*;
public class DBUtil {
public static Connection getConnection() throws Exception {
//1.加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
//2.创建连接
Connection connection = DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/nbcj?useSSL=true&characterEncoding=utf-8&user=root&password=123456”);
System.out.println(“创建连接成功”);
return connection;
}
public static void closeAll(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection){
if(resultSet !=null){
try {
resultSet.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();
}
}
}
}
然后进行删除操作
import Ningcai.Util.DBUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class delete {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
//1.加载驱动
try {
connection = DBUtil.getConnection();
//3.写sql语句
String sql = "delete from student where id=?";
//4.得到statement对象
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeAll(null,preparedStatement,connection);
}
}
}