My system is Window 10 English-US. I need to write some non-printable ASCII characters to a text file. So for eg for the ASCII value of 28, I want to write \u001Cw to the file. I don't have to do anything special when coded in Java. Below is my code in VBS
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = 2
objStream.Position = 0
objStream.CharSet = "utf-16"
objStream.WriteText ChrW(28) 'Need this to appear as \u001Cw in the output file
objStream.SaveToFile "C:\temp\test.txt", 2
objStream.Close
You need a read-write stream so that writing to it and saving it to file both work.
Other notes:
Const
all the constants in the code. Makes reading so much easier.With
block save quite some typing here.adTypeText
is not really necessary, that's the default anyway. But explicit is better than implicit, I guess.Position
to 0 on a new stream is superfluous.ChrW()
for ASCII-range characters. The stream'sCharset
decides the byte width when you save the stream to file. In RAM, everything is Unicode anyway (yes, even in VBScript).UTF-16LE
(which is the default and synonymous withUTF-16
) and big-endianUTF-16BE
, with the byte order reversed.You can achieve the same result with the FileSystemObject and its
CreateTextFile()
method:This is a little bit simpler, but it only offers a Boolean
Unicode
parameter, which switches between UTF-16 and ANSI (not ASCII, as the documentation incorrectly claims!). The solution withADODB.Stream
gives you fine-grained encoding choices, for example UTF-8, which is impossible with the FileSystemObject.For the record, there are two ways to create an UTF-8-encoded text file:
To create an UTF-8 file with BOM, the first code sample above can be used. To create an UTF-8 file without BOM, we can use two stream objects: