JAVA实现一键创建Markdown笔记模板

JAVA实现一键创建Markdown笔记模板

一、想法由来

在每天的学习过程中,都需要使用Typora来记笔记,记笔记时,需要一个模板,模板中只需要对首行插入一个<center>标签,然后插入我自己的名字和当天的日期。但是每次进去都要手动输入,就很麻烦。而Typora不可以自定义模板。所以就想,可不可以使用JAVA来自动生成文件,然后插入固定的一行内容即可。

二、项目需求

  1. 自动生成Markdow文件
  2. 自动向文件里插入<center>标签以及当天的日期
  3. 打包成exe文件,可以双击运行,自动打开文件

三、项目实现

  1. 首先需要新建文件,使用可以使用java.io.File;这个类来实现
public static void createFile(String fileName){
        File file = new File(fileName);

        // 如果存在,提示失败,返回false
        if (file.exists()){
            System.out.println("文件" + fileName + "已存在,创建失败!");
        }else {
            try {
                if (file.createNewFile()) {
                    System.out.println("创建文件成功:" + fileName);
                }else {
                    System.out.println("创建文件失败!!");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  1. 使用FileWriter将需要的内容写入到Markdown文件里
public static boolean insertInformation(String information, String path){
        try {
            // 读取要写入的文件
            FileWriter writerFile = new FileWriter(path);
            // 将信息写入文件
            writerFile.write(information);
            // 刷新缓冲区
            writerFile.flush();
            // 关闭资源
            writerFile.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
  1. 获取当天的日期,然后返回固定的需要插入信息
public static String getInformation(){
        String todayDate = getDate();
        return "<center>姓名:<u> MyName </u>&nbsp;&nbsp;&nbsp;&nbsp;日期:<u>"+todayDate+"</u></center>";

    }

    public static String getDate(){
        // 获取日期
        Date date = new Date();
        // 格式化日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 返回格式化后的日期
        return simpleDateFormat.format(date);
    }
  1. 打开最终的文件
public static String openFile(String path){

        try {
            Desktop.getDesktop().open(new File(path));
            return "打开成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "打开失败";
    }
  1. main方法的编写
public static void main(String[] args) {
        // 目录
        String dirName = "C:\\Users\\26465\\OneDrive\\桌面";

        // 文件名
        String fileName = "\\" + getDate();// 文件名使用当天的日期
        String path = dirName + fileName + ".md"; // 加入Markdown文件的后缀
        createFile(path);
        String information = getInformation();
        boolean successful = insertInformation(information, path);
        System.out.println(successful ? "插入数据成功" : "插入数据失败!!");
        System.out.println(openFile(path));

    }
  1. 使用exe4j Wizard 软件,将java文件转换成exe文件即可。

版权声明:本文为Soul_DJinWei原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。