最近用java做大量读取/xml/txt/文件时遇到了很多乱码不一致的问题。有的txt是gbk,有的xml又是gb2312。等格式,我目的是把这些文件中的数据提取可用信息保存到数据库。结果发现经程序很难判断文件编码格式。不知道该定义什么编码去读取,虽然java提供了Charset.defaultCharset()类,但我测试,还是没有c#提供的API类好使用。就是StreamReader,它还有一个很做棒的参数对象,就是Encoding.Default; 通过它可以不用指定读取编码,使用本地系统编码,并且写入的时候还可以指定编码写入,这不就达到了我们想要的目的,把多种编码统一。。。下面就上代码吧。。。很简单的...
/* * 由SharpDevelop创建。 * 用户: hubiao * 日期: 2014/5/2 * 时间: 9:45 */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Text; using System.IO; namespace encodeingUtils { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private String pathTemp; public MainForm() { InitializeComponent(); } public void Button1Click(object sender, System.EventArgs e) { buGo.Enabled = false; try{ //创建directory对象 DirectoryInfo directory = new DirectoryInfo(tbPath.Text); FileSystemInfo[] infos = directory.GetFileSystemInfos(); //临时存储文件 pathTemp = Path.GetTempPath()+"/"+Guid.NewGuid().ToString()+".dat"; //递归获取文件,并转码 fileList(infos); }catch(Exception xe){ MessageBox.Show(xe.Message); } File.Delete(pathTemp); MessageBox.Show("OK"); buGo.Enabled = true; } void MainFormLoad(object sender, EventArgs e) { comBoxDefautlCode.Items.AddRange(new Object[]{"utf-8","GBK","gb2312"}); } void BuShowClick(object sender, EventArgs e) { } public void fileList(FileSystemInfo[] fsins) { foreach(FileSystemInfo fs in fsins){ //判断文件 FileInfo file = fs as FileInfo; if(file!=null){ StreamReader sr = new StreamReader(file.FullName,Encoding.Default); StreamWriter sw = new StreamWriter(pathTemp,false,Encoding.GetEncoding(comBoxDefautlCode.Text)); for(string line = null;(line=sr.ReadLine())!=null;){ sw.WriteLine(line); } sw.Close(); sr.Close(); sr = new StreamReader(pathTemp,Encoding.Default); sw = new StreamWriter(file.FullName,false,Encoding.GetEncoding(comBoxDefautlCode.Text)); for(string line = null;(line=sr.ReadLine())!=null;){ sw.WriteLine(line); } sw.Close(); sr.Close(); } //判断文件夹 DirectoryInfo direct = fs as DirectoryInfo; if(direct!=null){ fileList(direct.GetFileSystemInfos()); } } } } }
程序图片
转换之后文件编码:
本程序的目的是为了把文件编码格式统一。如果文件内容编码不同,则也不能保正内容也正常转换
缺点:比如iso-8859-1的内容转换成utf-8。则可能失败。。。
优点:java文件,txt/xml/dat文件。只要都是能识别的内容,即转换成功就更大。