把文件夹的文件根据后缀名过滤,并以Markdown格式汇总到一个文件

导入依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>

获取字符集工具类

package www.taopanfeng.top.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 * @author TaoPanfeng
 * @version 1.0
 * @description
 * @date 2020-03-13 11:52
 */
public class MyFileUtils
{
    /**
     * @description 根据文件获取字符集【例如UTF8 GBK】
     * @param 文件字符串
     * @author TaoPanfeng
     * @date 2020-03-13 11:52
     */

    public static String charset(String path)
    {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try
        {
            boolean checked = false;
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
            bis.mark(0); // 读者注: bis.mark(0);修改为 bis.mark(100);我用过这段代码,需要修改上面标出的地方。
            // Wagsn注:不过暂时使用正常,遂不改之
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
            {
                bis.close();
                return charset; // 文件编码为 ANSI
            } else if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE)
            {
                charset = "UTF-16LE"; // 文件编码为 Unicode
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF)
            {
                charset = "UTF-16BE"; // 文件编码为 Unicode big endian
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF)
            {
                charset = "UTF-8"; // 文件编码为 UTF-8
                checked = true;
            }
            bis.reset();
            if (!checked)
            {
                while ((read = bis.read()) != -1)
                {
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF)
                    {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
                            // (0x80 - 0xBF),也可能在GB编码内
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF)
                    { // 也有可能出错,但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF)
                        {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF)
                            {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
            bis.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        //System.out.println("--文件-> [" + path + "] 采用的字符集为: [" + charset + "]");
        return charset;
    }
}

给类中新建测试方法

@Test
public void t00() throws Exception
{
    for (int i = 1; i < 50; i++)
    {
        String number = i < 10 ? "0" + i : "" + i;

        System.out.println(" @Test public void t" + number + "()throws Exception{}");
    }
}

(过程1)测试输出到文件

    @Test
    public void t01() throws Exception
    {
        Collection<File> files = FileUtils.listFiles(new File("D:/test/"),
                EmptyFileFilter.NOT_EMPTY,
                DirectoryFileFilter.INSTANCE);

        files.forEach((file) ->
        {
            String name = file.getName();
            try
            {

                String content = FileUtils.readFileToString(file, MyFileUtils.charset(file.getAbsolutePath()));
                StringBuilder sb = new StringBuilder();
                sb.append("# " + name + "\n");
                sb.append("```\n");
                sb.append(content + "\n");
                sb.append("```\n\n");
                FileUtils.write(new File("D:/test/result.md"), sb.toString(), "utf8", true);
            } catch (IOException e)
            {
                e.printStackTrace();
            }

        });
    }

(过程2)打印后缀名

    @Test
    public void t02() throws Exception
    {
        String mainPath = "D:/Everything/SVN/workspace/0303编码实现/trunk/Source/";
        String[] names = {"airflow", "data-service-security-enhance", "data-service-security-enhance-portal", "eip"};
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < names.length; i++)
        {
            Collection<File> files = FileUtils.listFiles(new File(mainPath + names[i]),
                    EmptyFileFilter.NOT_EMPTY,
                    DirectoryFileFilter.INSTANCE);

            files.forEach((file) ->
            {
                String suffix = FilenameUtils.getExtension(file.getName());
                if (suffix.equals("md") || suffix.equals("css"))
                {
                    System.out.println(file.getAbsolutePath());
                }
                set.add(suffix);

            });
            System.out.println(names[i] + "done...");
        }

        System.out.println(set.toString());

        // airflowdone...
        //data-service-security-enhancedone...
        //data-service-security-enhance-portaldone...
        //eipdone...
        //[, css, FDC, log, py, iml, js, conf, pid, eot, lst, sql, 20190723, java, ico, sh, xml, md, json,
        // yml, jar, woff2, html, class, map, zip, jpg, types, original, svg, gitignore, ttf, png, war, sample,
        // pack, woff, txt, 1, 2, meta, vm, name, cmd, idx, properties]
    }

(结果)最终实现

    @Test
    public void t03() throws Exception
    {
        //[css, py, js, conf, sql,java, sh, xml, json, yml, html ,properties]
        ArrayList<String> suffix_list = new ArrayList<>(Arrays.asList("css", "py", " js", "conf", " sql", "java", "sh", "xml", "json", "yml", "html", "properties"));

        String mainPath = "D:/Everything/SVN/workspace/0303编码实现/trunk/Source/";
        String[] names = {"airflow", "data-service-security-enhance", "data-service-security-enhance-portal", "eip"};
        for (int i = 0; i < names.length; i++)
        {
            Collection<File> files = FileUtils.listFiles(new File(mainPath + names[i]),
                    EmptyFileFilter.NOT_EMPTY,
                    DirectoryFileFilter.INSTANCE);

            files.forEach((file) ->
            {
                String suffix = FilenameUtils.getExtension(file.getName()).trim();
                if (suffix_list.contains(suffix))
                {
                    String name = file.getName();
                    try
                    {
                        String content = FileUtils.readFileToString(file, MyFileUtils.charset(file.getAbsolutePath()));
                        StringBuilder sb = new StringBuilder();
                        sb.append("# " + name + "\n");
                        sb.append("```" + suffix + "\n");
                        sb.append(content + "\n");
                        sb.append("```\n\n");
                        FileUtils.write(new File("D:/test/result.md"), sb.toString(), "utf8", true);
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
            //System.out.println(names[i] + " done...");
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 首先,您需要安装 Python 的 markdown 库,然后您可以使用以下代码来批量将 markdown 格式文件转换为 html 格式文件: ``` import os import markdown # 遍历指定文件夹中的 markdown 文件 for file in os.listdir("path/to/markdown/files"): # 判断文件是否是 markdown 文件 if file.endswith(".md"): # 读取 markdown 文件内容 with open(file, "r") as f: content = f.read() # 使用 markdown 库将 markdown 格式转换为 html 格式 html = markdown.markdown(content) # 将 html 代码写入新文件 with open(file[:-3] + ".html", "w") as f: f.write(html) ``` 该代码会遍历 "path/to/markdown/files" 文件夹中的所有 markdown 文件,然后使用 markdown 库将它们转换为 html 代码,并将 html 代码写入新的 html 文件中。 ### 回答2: 使用Python批量将Markdown文件导出为HTML文件的代码如下: ```python import os import markdown def convert_to_html(md_file): # 读取Markdown文件内容 with open(md_file, 'r', encoding='utf-8') as file: markdown_content = file.read() # 将Markdown内容转换为HTML html_content = markdown.markdown(markdown_content) # 修改文件后缀名为.html html_file = os.path.splitext(md_file)[0] + '.html' # 将HTML内容写入文件 with open(html_file, 'w', encoding='utf-8') as file: file.write(html_content) print(f'Successfully converted {md_file} to {html_file}') def batch_convert_to_html(md_folder): # 遍历文件夹下的所有Markdown文件 for root, dirs, files in os.walk(md_folder): for file in files: if file.endswith('.md'): md_file = os.path.join(root, file) convert_to_html(md_file) # 批量导出Markdown文件为HTML文件 md_folder = 'path/to/markdown/folder' batch_convert_to_html(md_folder) ``` 使用这段代码,首先我们定义了一个`convert_to_html`函数,该函数接收一个Markdown文件的路径作为参数。函数内部读取Markdown文件内容,并使用`markdown`模块将其转换为HTML内容。然后,我们修改文件后缀名为`.html`,并将HTML内容写入新文件中。 接下来,我们定义了`batch_convert_to_html`函数,该函数接收一个包含Markdown文件文件夹路径作为参数。函数内部使用`os.walk`方法遍历文件夹下的所有Markdown文件,并调用`convert_to_html`函数将其转换为HTML文件。 最后,我们设置了一个`md_folder`变量,指定包含Markdown文件文件夹路径,并调用`batch_convert_to_html`函数进行批量转换。你只需将`md_folder`变量修改为你的Markdown文件所在的文件夹路径即可。 ### 回答3: 使用Python批量导出Markdown格式文件为HTML文件的代码可以使用Python的标准库markdown和os模块。 首先,需要导入所需的模块: ``` import markdown import os ``` 在代码中,首先需要指定要处理的Markdown文件所在的文件夹和导出的HTML文件存放的文件夹: ``` input_folder = 'markdown_files_folder' # Markdown文件所在的文件夹 output_folder = 'html_files_folder' # 导出的HTML文件存放文件夹 ``` 然后,可以使用os模块的listdir函数获取指定文件夹下所有文件文件名: ``` file_names = os.listdir(input_folder) ``` 接下来,通过遍历上一步得到的文件名列表,使用markdown模块的markdown函数将Markdown文件转换为HTML格式的文本,并将结果写入对应的HTML文件: ``` for file_name in file_names: if file_name.endswith('.md'): # 构造输入和输出的文件路径 input_file = os.path.join(input_folder, file_name) output_file = os.path.join(output_folder, file_name.replace('.md', '.html')) # 读取Markdown文件内容 with open(input_file, 'r', encoding='utf-8') as f: markdown_text = f.read() # 转换为HTML格式 html_text = markdown.markdown(markdown_text) # 写入HTML文件 with open(output_file, 'w', encoding='utf-8') as f: f.write(html_text) ``` 以上就是使用Python批量导出Markdown格式文件为HTML文件的代码。通过遍历指定文件夹下的Markdown文件,将其逐个转换为HTML格式并写入到指定文件夹下的HTML文件中。请注意,上述代码中需要调整文件夹路径为实际使用的文件夹路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值