vb.net二进制怎么读取文件?
dim buff as byte()=system.text.encoding.utf8.getbytes(s)'这个就是utf8编码的byte数组。
然后把buff写入文件就行了。
把utf8编码的文件读取到byte数组数据,可以用system.text.encoding.utf8.getstring(buff)即可转换为字符串。
VB.Net中己不再使用Open来读写二进制文件,而是用BinaryReader/BinaryWriter来对二进制文件进行读写操作。
举例如下
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Imports System.Windows.Forms
Imports System.IO
Imports System.Text
Public Class Form1
'按下Button1按钮,创建一个二进制文件并写入一个浮点数
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
'创建文件准备写入
Dim myFile As New IO.FileStream("d:\data.bin", _
FileMode.Create, _
FileAccess.Write)
'写入二进制格式数据
Dim bw As New BinaryWriter(myFile)
'写入一个浮点数
Dim f As Single
f = 3.14159
bw.Write(f)
'关闭流
bw.Flush()
bw.Close()
'关闭文件
myFile.Close()
End Sub
'按下Button2按钮,从二进制文件并读入一个浮点数值并显示
Private Sub Button2_Click(sender As Object, _
e As EventArgs) Handles Button2.Click
'文件不如不存在则退出
If Not File.Exists("d:\data.bin") Then Exit Sub
'打开文件准备读
Dim myFile As New IO.FileStream("d:\data.bin", _
FileMode.Open, _
FileAccess.Read)
'按二进制格式读取数据
Dim br As New BinaryReader(myFile)
'读取一个浮点数
Dim f As Single
f = br.ReadSingle()
'关闭流
br.Close()
'关闭文件
myFile.Close()
'显示读出的内容
MessageBox.Show(f.ToString())
End Sub
End Class
读取二进制文件用的是fileget方法,写入二进制文件用的是fileput方法。
应用示例:将一批随机数保存在一个dat文件中,然后再将其提取到文本框中。
二进制文件的读写一批随机数的存取,程序为:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x, i, fn As Integer
Dim s As String = ""
fn = FreeFile()
FileOpen(fn, "d:\data.dat", OpenMode.Binary)
For i = 1 To 8
x = Int(Rnd() * 100)
s = s + Str(x)
FilePut(fn, x)
Next
FileClose(fn)
TextBox1.Text = s
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim x, fn As Integer
Dim s As String = ""
fn = FreeFile()
FileOpen(fn, "d:\data.dat", OpenMode.Binary)
Do While Not EOF(fn)
FileGet(fn, x)
s = s + Str(x) + " "
Loop
FileClose(fn)
TextBox1.Text = s
End Sub