`

批量把文件编码由GBK转为UTF8

阅读更多

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;

/**
 * 批量把文件编码由GBK转为UTF8,可以继续完善做成在命令行中执行的程序, 可以添加文件名过滤等功能,暂时未实现。
 * 
 */
public class FileGBK2UTF8 {

	public static void main(String[] args) {
		// 需要转换的文件目录
		String fromPath = "D:\\input";
		// 转换到指定的文件目录
		String toPath = "D:\\output";

		info("start transform [from path]={0} [to path]={1}", fromPath, toPath);

		// 递归取到所有的文件进行转换
		transform(fromPath, toPath);
	}

	/**
	 * 把一个目录中的文件转换到另一个目录中
	 * 
	 * @param fromPath
	 *            -- 来源文件目录
	 * @param toPath
	 *            -- 目标文件目录
	 * @return
	 */
	public static boolean transform(String fromPath, String toPath) {
		File ftmp = new File(fromPath);
		if (!ftmp.exists()) {
			info("转换文件路径错误!");
			return false;
		}

		info("frompath is [{0}], topath is [{1}]", fromPath, toPath);

		// 如果是文件,则转换,结束
		if (ftmp.isFile()) {
			byte[] value = fileToBytes(fromPath);
			String content = convEncoding(value, "gbk", "utf-8");
			return saveFileUtf8(toPath, content);
		} else {
			// 查找目录下面的所有文件与文件夹
			File[] childFiles = ftmp.listFiles();
			for (int i = 0, n = childFiles.length; i < n; i++) {
				File child = childFiles[i];
				String childFrom = fromPath + "/" + child.getName();
				String childTo = toPath + "/" + child.getName();

				transform(childFrom, childTo);
			}
		}

		return true;
	}

	/**
	 * 把文件内容保存到指定的文件中,如果指定的文件已存在,则先删除这个文件, 如果没有则创建一个新文件,文件内容采用UTF-8编码方式保存。
	 * 如果指定的文件路径不存在,则先创建文件路径,文件路径从根目录开始创建。
	 * 
	 * @param fileName
	 *            -- 文件路径
	 * @param content
	 *            -- 文件内容
	 * @return
	 */
	public static boolean saveFileUtf8(String fileName, String content) {
		if (fileName == null || fileName.length() == 0)
			return false;
		if (content == null)
			return false;

		// 路径中的\转换为/
		fileName = fileName.replace('\\', '/');
		// 处理文件路径
		createPath(fileName.substring(0, fileName.lastIndexOf('/')));

		File file = null;
		FileOutputStream out = null;
		try {
			// 创建或修改文件
			file = new File(fileName);

			if (file.exists()) {
				file.delete();
			} else {
				file.createNewFile();
			}

			out = new FileOutputStream(file);
			// 添加三个字节标识为UTF-8格式,也是BOM码
			// out.write(new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF});
			out.write(content.getBytes("UTF-8"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * 把文件内容转换为字节数组输出。
	 * 
	 * @param fileName
	 *            -- 文件名
	 * @return
	 */
	public static byte[] fileToBytes(String fileName) {
		FileInputStream ins = null;
		ByteArrayOutputStream bos = null;
		try {
			// 创建文件读入流
			ins = new FileInputStream(new File(fileName));
			// 创建目标输出流
			bos = new ByteArrayOutputStream();

			// 取流中的数据
			int len = 0;
			byte[] buf = new byte[256];
			while ((len = ins.read(buf, 0, 256)) > -1) {
				bos.write(buf, 0, len);
			}

			// 目标流转为字节数组返回到前台
			return bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (ins != null) {
					ins.close();
					ins = null;
				}
				if (bos != null) {
					bos.close();
					bos = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 检查指定的文件路径,如果文件路径不存在,则创建新的路径, 文件路径从根目录开始创建。
	 * 
	 * @param filePath
	 * @return
	 */
	public static boolean createPath(String filePath) {
		if (filePath == null || filePath.length() == 0)
			return false;

		// 路径中的\转换为/
		filePath = filePath.replace('\\', '/');
		// 处理文件路径
		String[] paths = filePath.split("/");

		// 处理文件名中没有的路径
		StringBuilder sbpath = new StringBuilder();
		for (int i = 0, n = paths.length; i < n; i++) {
			sbpath.append(paths[i]);
			// 检查文件路径如果没有则创建
			File ftmp = new File(sbpath.toString());
			if (!ftmp.exists()) {
				ftmp.mkdir();
			}

			sbpath.append("/");
		}

		return true;
	}

	/**
	 * 取路径中的文件名
	 * 
	 * @param path
	 *            -- 文件路径,含文件名
	 * @return
	 */
	public static String getFileName(String path) {
		if (path == null || path.length() == 0)
			return "";

		path = path.replaceAll("\\\\", "/");
		int last = path.lastIndexOf("/");

		if (last >= 0) {
			return path.substring(last + 1);
		} else {
			return path;
		}
	}

	/**
	 * 字符串的编码格式转换
	 * 
	 * @param value
	 *            -- 要转换的字符串
	 * @param oldCharset
	 *            -- 原编码格式
	 * @param newCharset
	 *            -- 新编码格式
	 * @return
	 */
	public static String convEncoding(byte[] value, String oldCharset,
			String newCharset) {
		OutputStreamWriter outWriter = null;
		ByteArrayInputStream byteIns = null;
		ByteArrayOutputStream byteOuts = new ByteArrayOutputStream();
		InputStreamReader inReader = null;

		char cbuf[] = new char[1024];
		int retVal = 0;
		try {
			byteIns = new ByteArrayInputStream(value);
			inReader = new InputStreamReader(byteIns, oldCharset);
			outWriter = new OutputStreamWriter(byteOuts, newCharset);
			while ((retVal = inReader.read(cbuf)) != -1) {
				outWriter.write(cbuf, 0, retVal);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (inReader != null)
					inReader.close();
				if (outWriter != null)
					outWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String temp = null;
		try {
			temp = new String(byteOuts.toByteArray(), newCharset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// System.out.println("temp" + temp);
		return temp;
	}

	/**
	 * 显示提示信息
	 * 
	 * @param message
	 *            -- 信息内容
	 * @param params
	 *            -- 参数
	 */
	private static void info(String message, Object... params) {
		message = MessageFormat.format(message, params);

		System.out.println(message);
	}
}
 
分享到:
评论

相关推荐

    批量将Java源代码文件的编码从GBK转为UTF-8

    老项目采用GBK编码格式,而新项目采用的UTF-8编码格式,如果直接把Java源代码复制到Eclipse中所有的中文信息会出现乱码。所以写了个小的方法类,将java文件的编码格式从GBK转UTF-8

    GBK批量转utf8(支持整个目录)

    "GBK批量转utf8(支持整个目录)"这个工具正是为了解决在处理多语言文件时遇到的编码问题。当你需要将一个使用GBK编码的目录全部转换为UTF-8编码时,这个工具可以大大提高效率。它能遍历指定目录下的所有文件,包括...

    Eclipse项目的GBK编码转为UTF-8插件

    总的来说,"Eclipse项目的GBK编码转为UTF-8插件"是解决GBK到UTF-8编码转换问题的有效工具,它简化了开发者的工作流程,提高了代码管理的效率。对于那些经常需要处理不同编码格式项目的人来说,这样的工具无疑是非常...

    判断文件编码格式和批量将gbk转为utf-8

    标题"判断文件编码格式和批量将gbk转为utf-8"涉及两个主要知识点: 1. **文件编码识别**:判断文件编码格式通常是为了确保正确读取和处理文件内容。这可以通过各种工具或编程库实现。例如,Python中的`chardet`库...

    使用eclipse插件批量将Java源代码文件的编码从GBK(或其他编码)转为UTF-8

    以上就是关于“使用Eclipse插件批量将Java源代码文件的编码从GBK(或其他编码)转为UTF-8”的详细解释,希望对你在进行编码格式转换时有所帮助。在实际操作中,还需要根据具体的插件和Eclipse版本进行适当的调整。

    utf8 gbk big5 多编码批量转换软件

    "utf8 gbk big5 多编码批量转换软件"是一款专为处理这些需求设计的工具,它能够帮助用户方便地将大量文件从UTF-8、GBK或BIG5等不同的字符编码格式批量转换为其他格式。在网站开发、数据迁移、文本处理等领域,这样的...

    php 编码相互转换类(gbk转换utf8)

    例如,将GBK编码的字符串转为UTF-8,可以写成`iconv("GBK", "UTF-8//IGNORE", $str)`。`//IGNORE`选项用于忽略无法转换的字符,避免出现错误。 然而,`iconv`有时会遇到一些问题,比如遇到未知的或非法的字符时,...

    Linux 下批量 gbk 转 utf-8 编码脚本

    Linux 下批量 gbk 转 utf-8 编码脚本

    Shell脚本把文件从GBK转为UTF-8编码

    在某些情况下,我们可能需要将GBK编码的文件转换为UTF-8编码,以便更好地兼容国际化的软件环境或者满足网络传输的要求。Shell脚本提供了一种高效且灵活的方式来批量处理这种转换任务。下面我们将详细讲解如何使用...

    将汉字转为UTF8,支持文件转换格式

    "将汉字转为UTF8,支持文件转换格式"这个标题涉及到的关键知识点是字符编码的转换,特别是从GBK(或GB2312)编码到UTF-8编码的转换,以及批量文件处理。 UTF-8是一种广泛使用的Unicode字符编码,能够表示世界上几乎...

    易语言TXT快速转换UTF-8源码

    这个易语言源码的主要目标是将那些可能采用其他编码(如GBK、GB2312等)的TXT文件转换为UTF-8编码。在处理中文字符时,GBK等编码可能会出现乱码问题,而UTF-8编码则可以很好地解决这个问题,确保在不同系统和环境下...

    转换为GB2312.bat转换为UTF8.bat

    标题和描述中提到的"转换为GB2312.bat转换为UTF8.bat"暗示了这是一个批处理(batch script)文件,用于在两种不同的字符编码之间进行转换:GBK(GB2312)和UTF-8。GBK是中国大陆广泛使用的简体中文编码标准,而UTF-8...

    编码批量转换项目

    这是编码批量转换的工具,有java环境的直接运行就好 ,主要是用来转换文件的编码,比如一个eclipse的默认编码是GBK,另一个eclipse的编码是UTF-8,把GBK的项目拿到utf-8的eclipse去运行,中文肯定乱码,这时需要把...

    GBK文件夹转化UTF-8 支持文件名

    // 读取GBK编码的文件内容并转为UTF-8 String content = new String(Files.readAllBytes(sourcePath), Charset.forName("GBK")); Files.write(Paths.get(targetFilePath), content.getBytes(Charset.forName("UTF...

    DOS或CMD命令下文本UTF8转ANSI软件

    标题提到的“DOS或CMD命令下文本UTF8转ANSI软件”是指在命令提示符(Command Prompt,简称CMD)环境中运行的程序,可以将使用UTF8编码的文本文件转换为使用ANSI编码的文件。UTF8是一种广泛使用的字符编码标准,它...

    使用python批量转换文件编码为UTF-8的实现

    本来一开始的思路还是比较清晰,觉得也比较简单,天真的认为用GBK的方式读取出文件内容,然后UTF8写入就好了,可是在实际的操作中我发现我就是太天真了,出现了大量的问题,比如说: 怎么查看文件的编码方式 好吧我...

    编码批量转换.jar

    这是编码批量转换的工具,有java环境的直接运行就好 ,主要是用来转换文件的编码,比如一个eclipse的默认编码是GBK,另一个eclipse的编码是UTF-8,把GBK的项目拿到utf-8的eclipse去运行,中文肯定乱码,这时需要把...

    守望文件编码转换器

    例如,一个GBK编码的文件在UTF-8环境下打开可能会出现乱码,此时就需要通过转换器将其转为UTF-8编码。在实际操作中,用户只需选择待转换的文件,指定输入编码(源文件的编码格式)和输出编码(希望转换的目标编码)...

    eclipse文件编码设置、转换原理与实用工具

    结合上述a、b两个工具的工具用以批量转换当前eclipse项目的文件的二进制编码为另外的编码(一般默认编码为gbk,建议转为utf-8); d.汉字转unicode编码(unicode编码如\u5546),在编码为iso-8839-1的文件中显示...

Global site tag (gtag.js) - Google Analytics