批量转换编码格式,针对csv和txt文件编码格式。

由于第三方给出的csv编码格式问题导致无法导入指定的库表,网上找了许多转换的插件总是不满意。折腾了大半天想想还是自己改造下吧。该工具包解决了几乎所有的编码问题,若是不足之处请指出。由于文件暂存在String类型里面,要是文件太大的话会报内存溢出的错误可以自行调整下代码。



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

public class FileCharsetConverter {  

    public static void main(String[] args) throws Exception { 
        String dirPath ="C:\\Users\\oftoo\\Desktop\\服务默认\\原编码\\xx\\xx";
        File dirFile = new File(dirPath);
        File[] files = dirFile.listFiles();
        if (null == files) {
          System.out.println("路径:" + dirPath + ",该文件夹下没有文件");
        } else {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String destFileName = file.getCanonicalPath();
                File destFile = new File(destFileName);
                if (destFile.exists()) {
                    convert(destFile.getCanonicalPath(),  
                        "UTF-16LE", "GBK", new FilenameFilter() {  
                            @Override  
                            public boolean accept(File dir, String name) {  
                                return name.endsWith("csv");  
                            }  
                        });  
                } else {
                    System.out.println("路径:" + dirPath + ",该文件夹下没有文件");
                }
            }
            System.out.println("编码转换结束");
        }

        /*convert("C:\\Users\\xieyh\\Desktop\\测试编码\\LRL_HairStore_Tmall_Acxiom_Transaction_20170619.csv",  
                "UTF-16LE", "GBK", new FilenameFilter() {  
                    @Override  
                    public boolean accept(File dir, String name) {  
                        return name.endsWith("csv");  
                    }  
                });  */

    }  

    public static String getParentPath(File file) {
        if (null != file && file.exists()) {
            return file.getParent();
        }
        return "";
    }

    /** 
     * 把指定文件或目录转换成指定的编码 
     *  
     * @param fileName 
     *            要转换的文件 
     * @param fromCharsetName 
     *            源文件的编码 
     * @param toCharsetName 
     *            要转换的编码 
     * @throws Exception 
     */  
    public static void convert(String fileName, String fromCharsetName,  
            String toCharsetName) throws Exception {  
        convert(new File(fileName), fromCharsetName, toCharsetName, null);  
    }  

    /** 
     * 把指定文件或目录转换成指定的编码 
     *  
     * @param file 
     *            要转换的文件或目录 
     * @param fromCharsetName 
     *            源文件的编码 
     * @param toCharsetName 
     *            要转换的编码 
     * @throws Exception 
     */  
    public static void convert(File file, String fromCharsetName,  
            String toCharsetName) throws Exception {  
        convert(file, fromCharsetName, toCharsetName, null);  
    }  

    /** 
     * 把指定文件或目录转换成指定的编码 
     *  
     * @param file 
     *            要转换的文件或目录 
     * @param fromCharsetName 
     *            源文件的编码 
     * @param toCharsetName 
     *            要转换的编码 
     * @param filter 
     *            文件名过滤器 
     * @throws Exception 
     */  
    public static void convert(String fileName, String fromCharsetName,  
            String toCharsetName, FilenameFilter filter) throws Exception {  
        convert(new File(fileName), fromCharsetName, toCharsetName, filter);  
    }  

    /** 
     * 把指定文件或目录转换成指定的编码 
     *  
     * @param file 
     *            要转换的文件或目录 
     * @param fromCharsetName 
     *            源文件的编码 
     * @param toCharsetName 
     *            要转换的编码 
     * @param filter 
     *            文件名过滤器 
     * @throws Exception 
     */  
    public static void convert(File file, String fromCharsetName,  
            String toCharsetName, FilenameFilter filter) throws Exception {  
        if (file.isDirectory()) {  
            File[] fileList = null;  
            if (filter == null) {  
                fileList = file.listFiles();  
            } else {  
                fileList = file.listFiles(filter);  
            }  
            for (File f : fileList) {  
                convert(f, fromCharsetName, toCharsetName, filter);  
            }  
        } else {  
            if (filter == null  
                    || filter.accept(file.getParentFile(), file.getName())) {  
                String fileContent = getFileContentFromCharset(file,  
                        fromCharsetName);  
                saveFile2Charset(file, toCharsetName, fileContent);  
            }  
        }  
    }  

    /** 
     * 以指定编码方式读取文件,返回文件内容 
     * 
     * @param file 
     *            要转换的文件 
     * @param fromCharsetName 
     *            源文件的编码 
     * @return 
     * @throws Exception 
     */  
    public static String getFileContentFromCharset(File file,  
            String fromCharsetName) throws Exception {  
        if (!Charset.isSupported(fromCharsetName)) {  
            throw new UnsupportedCharsetException(fromCharsetName);  
        }  
        InputStream inputStream = new FileInputStream(file);  
        InputStreamReader reader = new InputStreamReader(inputStream,  
                fromCharsetName);  
        char[] chs = new char[(int) file.length()];  
        reader.read(chs);  
        String str = new String(chs).trim();  
        reader.close();  
        return str;  
    }  

    /** 
     * 以指定编码方式写文本文件,存在会覆盖 
     *  
     * @param file 
     *            要写入的文件 
     * @param toCharsetName 
     *            要转换的编码 
     * @param content 
     *            文件内容 
     * @throws Exception 
     */  
    public static void saveFile2Charset(File file, String toCharsetName,  
            String content) throws Exception {  
        if (!Charset.isSupported(toCharsetName)) {  
            throw new UnsupportedCharsetException(toCharsetName);  
        }  
        OutputStream outputStream = new FileOutputStream(file);  
        OutputStreamWriter outWrite = new OutputStreamWriter(outputStream,  
                toCharsetName);  
        outWrite.write(content);  
        outWrite.close();  
    }  

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
批量修改csv文件编码格式,首先来解释一下编码格式编码格式是一种将字符转换成二进制数字的规则,不同的编码格式使用不同的规则进行转换。在Python中,我们可以使用csv模块来读取和写入csv文件。 要批量修改csv文件编码格式,我们可以按照以下步骤进行操作: 1. 导入所需的模块:首先,要修改编码格式,我们需要导入csv和codecs模块。csv模块用于读取和写入csv文件,codecs模块用于处理编码格式转换。 2. 创建一个文件名列表:我们需要获取所有要修改的csv文件文件名列表。可以使用os模块的listdir函数来获取指定目录中的所有文件名。 3. 循环遍历文件名列表:使用一个for循环来遍历文件名列表,并对每个文件进行编码格式的修改操作。 4. 打开文件并读取内容:使用csv模块的reader函数打开csv文件,并通过循环遍历每一行来读取文件内容。 5. 修改编码格式并写入新文件:使用codecs模块的open函数以新的编码格式打开文件,并将读取的每一行写入新文件。 6. 关闭文件:在修改完成后,关闭原来的文件和新文件。 下面是一个示例代码片段,用于批量修改csv文件编码格式为utf-8: ```python import csv import codecs import os # 创建一个文件名列表 file_list = os.listdir("文件夹路径") # 循环遍历文件名列表 for file_name in file_list: # 打开原文件和新文件,使用utf-8编码格式 with codecs.open("文件夹路径/" + file_name, "r", encoding="原编码格式") as csv_file: with codecs.open("文件夹路径/" + file_name + "_new", "w", encoding="utf-8") as new_csv_file: # 读取原文件内容并写入新文件 csv_reader = csv.reader(csv_file) csv_writer = csv.writer(new_csv_file) for row in csv_reader: csv_writer.writerow(row) # 关闭原文件和新文件 csv_file.close() new_csv_file.close() ``` 请注意替换示例代码中的"文件夹路径"为你要操作的文件夹路径,同时将"原编码格式"替换为你的csv文件的当前编码格式。 这就是使用Python批量修改csv文件编码格式的基本步骤。你可以根据具体的需求做一些修改,比如控制文件名的命名规则、处理不同的编码格式等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值