定义一个接口
public interface newsDao {
public list <news> getNews();
}
定义实体类 : 定义属性 get 和 set 方法
public class news (
private string title ;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
)
定义数据连接类 :
public class DBUtil {
private static final String url = "jdbc:mysql://localhost:3306/news";
private static final String user = "root";
private static final String password = "hbtt";
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);0
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
定义实现类 : 实现接口的方法
public class NewsDaoImpl implements NewsDao{
public list <news> getName(){
list<news> list = new arrayList<news> ();
Connection conn = DBUtil.getConnection();// get connection 为静态方法 。可用类名直接调用
PreparedStatement prepStmt = null;
ResultSet rs = null;
String sql = "selext *from news";
prepstmt =conn.prepareStatement(sql);
rs = prepStmt.executeQuery();
while (rs.next()){
News new = new News();
new.setTitle (rs.setString ("title");
}
4“ 文件的读取
public static String readFile(String fileName)
FileReader fr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String tmp = br.readLine();
while(tmp != null){
sb.append(tmp).append("\r\n");
tmp = br.readLine();
文件的写入
public static void writeFile(String content, String fileName){
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
吧数据库中的内容写入HTML文件
private newdao dao = new NewsDaoImpl();'
public void replaceContent(){
String path ="d/html/";
String templateContent = FileUtil.readLine(path +"template.html" );
lisr<News> list =dao.getNews();
for (News n :list ) {
String content=templateContent.replace("#{title}",n.getTitle());
FileUtil .writeFile (content , path + n.getTitle() + ".html );