Home > 零敲碎打 > [VBS]文件批量转编码

[VBS]文件批量转编码

工作中需要将大量GB2312编码的文件转换为UTF-8编码,Baidu找了一段很实用的VBS可以有效解决问题。
使用方法也很简单,添加到工程调用ConvertFile即可。需要注意的是Adodb.Stream方式生成的UTF-8文件的头部会抱憾3个字节的BOM,处理PHP之类的无BOM要求的文件时需要注意一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Function ConvertFile(FileUrl)
    SrcCode = "gb2312"    ‘源编码
    DestCode = "utf-8"       ‘目标编码
    Call WriteToFile(FileUrl, ReadFile(FileUrl, SrcCode), DestCode)
End Function
 
Function ReadFile(FileUrl, CharSet)
    Dim Str
    Set stm = CreateObject("Adodb.Stream")
    stm.Type = 2
    stm.Mode = 3
    stm.CharSet = CharSet
    stm.Open
    stm.LoadFromFile FileUrl
    Str = stm.readtext
    stm.Close
    Set stm = Nothing
    ReadFile = Str
End Function
 
Function WriteToFile(FileUrl, Str, CharSet)
    Set stm = CreateObject("Adodb.Stream")
    stm.Type = 2
    stm.Mode = 3
    stm.CharSet = CharSet
    stm.Open
    stm.WriteText Str
    stm.SaveToFile FileUrl, 2
    stm.flush
    stm.Close
    Set stm = Nothing
End Function

参考
http://www.cnblogs.com/fanzhidongyzby/p/3782143.html
http://blog.csdn.net/caikanxp/article/details/5614901

Categories: 零敲碎打 Tags: ,
  1. No comments yet.
  1. No trackbacks yet.