zl程序教程

您现在的位置是:首页 >  Java

当前栏目

杨校老师课堂之Html页面快速转为jsp页面之工具类【简直太简单好用】

2023-03-20 14:58:30 时间

借原型编写助工jsp页面时,会因递归有大量的html页面,手动更改为jsp页面,造成时间浪费,所以通过下面的工具类就可以快速完成html页面转为jsp页面的过程了。

增加框架模块
添加web模块支持
静态资源及网页拷贝到web内
在src下右键创建 Java Class
命名为:
将下方代码拷贝进去:
htmlTojsppackage cn.javabs.util;

import java.io.*;

public class HtmlTranJspUtil {

    public static void main(String[] args) throws IOException {
        File file = new File("web");
        changeTojsp(file);
    }


    /**
     * @throws IOException
     * @Title: changeTojsp
     * @Description: 递归遍历文件夹所有文件,文件夹下所有html文件转换成jsp
     * @param : file
     * @return: void
     * @throws
     */
    public static void changeTojsp(File file) throws IOException {
        File[] files = file.listFiles();
        for (File a : files) {
            if (a.isDirectory()) {
                changeTojsp(a);
            }
            htmlTojsp(a);
        }
    }



    /**
     *
     * @Title:         htmlTojsp
     * @Description:   将html文件转换成jsp文件,并转换成utf-8字符集
     * @param:         @param file
     * @return:        void
     * @throws
     */
    private static void htmlTojsp(File file) throws IOException {
        String name = file.getName();

        //获取文件名,文件名以html结尾的进入if分支
        if (name.endsWith(".html")) {
            //在相同的目录下创建一个文件名相同的jsp文件
            File tempFile = new File(file.getAbsolutePath().replace(".html", ".jsp"));

            //copy文件  将html文件内容copy到jsp中
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            FileOutputStream outFile = new FileOutputStream(tempFile);
            OutputStreamWriter ow = new OutputStreamWriter(outFile, "UTF-8");

            //添加utf-8字符集
            String s = "<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
";
            ow.write(s, 0, s.length());

            //copy内容
            char[] buffer = new char[1024];
            int i = 0;
            while ((i = isr.read(buffer)) != -1) {
                ow.write(buffer, 0, i);
            }

            //关闭流
            ow.close();
            isr.close();
            outFile.close();

            // 复制完成删除htnl文件
            file.delete();
        }
    }
}