文件格式转换

文件格式转换

import codecs
import os

def convert(filename):
    # 打开ISO-8859编码的文件
    with codecs.open(filename, 'r', encoding='gb2312') as input_file:
        content = input_file.read()

    # 将ISO-8859编码的字符串转换为UTF-8编码的字符串
    content_utf8 = content.encode('utf-8')

    # 将UTF-8编码的字符串(bytes对象)转换为字符串
    content_utf8_str = content_utf8.decode('utf-8')

    # 将字符串写入文件
    with codecs.open(filename, 'w', encoding='utf-8') as output_file:
        output_file.write(content_utf8_str)

def visit_folder(folder_path):
    # 遍历文件夹中的所有文件和子文件夹
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            convert(file_path)

        elif os.path.isdir(file_path):
            # 如果是文件夹,则递归调用visit_folder函数
            visit_folder(file_path)

visit_folder(r'C:\Desktop\test')
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class UTF8ToGB2312ConverterLocal {
//文件操作
    public static void transform1(File file) {
        try {
            // 读取UTF-8文件
            FileInputStream fis = new FileInputStream(file);
            String charset = detectCharset(file);
            if (file.getName().equals("application.yml")) return;
            if (!charset.equals("UTF-8")) return;
            System.out.println(file.getName());
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            // 写入GB2312文件
            File tempFile = new File("temp.txt");
            FileOutputStream fos = new FileOutputStream(tempFile);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GB2312");
            BufferedWriter bw = new BufferedWriter(osw);

            String line;
            while ((line = br.readLine()) != null) {
               // System.out.println(line);
                String gb2312Line = transform4(line);
               // System.out.println(gb2312Line);
                if (gb2312Line==null) System.out.println(file.getAbsolutePath());
                bw.write(gb2312Line);
                bw.newLine();
            }

            br.close();
            bw.close();
            file.delete();
            tempFile.renameTo(file);
            System.out.println("ok!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//转换操作
    public static String transform4(String utf8String) {

            // 将UTF-8编码的字符串转换为字节数组
            byte[] utf8Bytes = utf8String.getBytes(Charset.forName("UTF-8"));

            // 创建UTF-8编码和GB2312编码的Charset对象
            Charset utf8Charset = Charset.forName("UTF-8");
            Charset gb2312Charset = Charset.forName("GB2312");

            // 创建CharsetDecoder和CharsetEncoder对象
            CharsetDecoder utf8Decoder = utf8Charset.newDecoder();
            CharsetEncoder gb2312Encoder = gb2312Charset.newEncoder();

            try {
                // 将UTF-8编码的字节数组解码为CharBuffer
                CharBuffer utf8CharBuffer = utf8Decoder.decode(ByteBuffer.wrap(utf8Bytes));

                // 将解码后的CharBuffer编码为GB2312编码的ByteBuffer
                ByteBuffer gb2312ByteBuffer = gb2312Encoder.encode(utf8CharBuffer);

                // 将GB2312编码的ByteBuffer转换为字节数组
                byte[] gb2312Bytes = new byte[gb2312ByteBuffer.remaining()];
                gb2312ByteBuffer.get(gb2312Bytes);

                // 将字节数组转换为GB2312编码的字符串
                String gb2312String = new String(gb2312Bytes, Charset.forName("GB2312"));

                System.out.println("UTF-8: " + utf8String);
                System.out.println("GB2312: " + gb2312String);
                return gb2312String;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

//格式检测
    public static String detectCharset(File file) throws IOException {
        Path path = Paths.get(file.getAbsolutePath());
        CharsetDetector detector = new CharsetDetector();
        detector.setText(Files.readAllBytes(path));
        CharsetMatch match = detector.detect();
        return match.getName();
    }

//单个文件夹格式转换
    public static void transform(String folderPath) throws IOException {
        File folder = new File(folderPath);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                transform1(file);
            }
        }
    }

//单个文件夹格式检测
    public static void checkFilesCharset(String folderPath) throws IOException {
        File folder = new File(folderPath);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String charset = detectCharset(file);
                System.out.println(file.getName() + " is "+charset);
                if (charset.contains("GB")) {
                    System.out.println(file.getName() + " is GBK");
                } else {
                    System.out.println(file.getName() + " is not GBK");
                }
            }
        }
    }
//递归格式转换
    public static void traverseFolderTransform(File folder) throws FileNotFoundException {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        traverseFolderTransform(file);
                    } else {
                        transform1(file);
                    }
                }
            }
        } else {
            System.out.println(folder.getAbsolutePath());
        }
    }
//递归格式监测
    public static void traverseFolderDetect(File folder) throws IOException {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        traverseFolderDetect(file);
                    } else {
                        String charset = detectCharset(file);
//                        System.out.println(file.getName() + " is "+charset);
                        if (charset.contains("GB")) {
                            System.out.println(file.getName() + " is GBK");
                        } else {
  //                          System.out.println(file.getName() + " is not GBK");
                        }
                    }
                }
            }
        } else {
            System.out.println(folder.getAbsolutePath());
        }
    }


    public static void main(String[] args) throws IOException {
       //     transform("D:\\Desktop\\input");
    //    checkFilesCharset("D:\\Desktop\\output");
        traverseFolderDetect(new File("D:\\Desktop\\server\\gray\\server_RERAT"));
    // traverseFolderTransform(new File("D:\\Desktop\\server\\gray\\server_RERAT"));
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
图像文件格式转换是指将一种图像文件格式转换为另一种图像文件的操作。这种操作通常用于不同图像编辑软件或设备之间文件的兼容性转换。 在C语言中,可以通过使用相应的图像处理库来实现图像文件格式转换。其中,最常用的图像处理库包括OpenCV和ImageMagick。 在使用这些图像处理库进行图像文件格式转换时,通常需要按照以下步骤进行: 1. 导入库文件:在C语言中,首先需要在代码中导入相关的图像处理库文件,以便使用库中提供的函数和方法。 2. 加载图像:使用图像处理库提供的函数或方法,将需要进行格式转换的图像文件加载到内存中。通常,图像文件可以通过指定路径的方式进行加载,或者直接从内存中进行加载。 3. 格式转换:通过调用图像处理库中提供的函数或方法,将加载到内存中的图像文件进行格式转换。函数或方法会根据指定的转换规则,将图像文件转换为目标格式。转换过程中,可能还需要进行一些参数的设置,如图像的压缩比、色彩空间的转换等。 4. 保存图像:将转换后的图像文件保存到磁盘中。保存过程通常也需要指定保存路径和目标文件名。 5. 释放资源:在图像文件格式转换完成后,需要释放之前加载到内存中的图像资源,以便释放内存空间。 综上所述,通过使用C语言中的图像处理库,我们可以实现图像文件格式转换的功能。这种转换能够实现不同图像文件格式之间的互相转换,为后续的图像处理工作提供了更多的选择和便利。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值