liut

liut.xyz

从简书迁hugo Jianshu2hugo

Posted at — Sep 26, 2017

体验了一把hugo,感觉很良好,就迁过来了。。。

首先,简书有导出文章功能,很赞!导出后是没办法直接在hugo使用的,因为hugo需要文件头,简书是没有的,就自己动手写了一段 java 代码,给文章加头,如下

    /**
     * 添加文件头
     * 用于简书导出文档转HUGO,具体格式请自调整
     *
     * @author Liut
     */
    @Test
    public void jianshu2hugo() throws IOException {
        File sourceDir = new File("D:/js2hugo/sourceDir");  // 源文件
        File outputDir = new File("D:/js2hugo/outputDir");  // 输出文件
        if (!sourceDir.exists()) sourceDir.mkdir();
        if (!outputDir.exists()) outputDir.mkdir();

        System.out.println("sourceDir != null >> " + sourceDir != null);

        for (File sourceFile : sourceDir.listFiles()) {
            String fileName = sourceFile.getName();
            System.out.println("===============");

            // 具体文件头,请根据需要拼装,应该也适用hexo
            StringBuilder builder = new StringBuilder();
            builder.append("+++\n\n");
            builder.append("banner = \"\"\n\n");
            // 分类
            builder.append("categories = [\"others\"]\n\n");
            // 日期
            builder.append("date = \"").append("2017-09-23T15:15:15+08:00").append("\"\n\n");
            // 描述
            builder.append("description = \"欲知详情,请点击标题\"\n\n");
            builder.append("images = []\n\n");
            builder.append("menu = \"\"\n\n");
            // TAG
            builder.append("tags = [\"from jianshu\"]\n\n");
            // 标题
            builder.append("title = \"").append(fileName.replace(".md", "")).append("\"\n\n");
            builder.append("+++\n\n");

            // 具体动作,其实就是复制操作,复制前先加上文件头
            File input = new File(sourceDir + File.separator + fileName);
            File output = new File(outputDir + File.separator + fileName);
            System.out.println("开始操作 >> " + input.toPath());
            InputStream is = new FileInputStream(input);
            OutputStream os = new FileOutputStream(output);
            byte[] buffer = new byte[1024];
            int len;
            os.write(builder.toString().getBytes());
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            System.out.println("操作结束 >> " + output.toPath());
        }

    }

嗯,不过尴尬的是我简书里并没有几篇文章是值得转的。。。

comments powered by Disqus