主题:[原创]文本文件的7种读入方法
Private Sub LoadTxtFile(fName As String, Index As Integer)
On Error GoTo 100
Dim St As String, Z As String, fLen As Long, i As Long, DAT() As Byte, fs, fi
Select Case Index
Case 0 '常见的方法,一行一行地读入
Open fName For Input As #1
Do Until EOF(1)
Line Input #1, Z
St = St & Z & vbCrLf
Loop
Close #1
Text1 = St
Case 1 '用FSO一行一行地读入,要预先知道行数
Set fs = CreateObject("Scripting.FileSystemObject")
Set fi = fs.opentextFile(fName, 1)
For i = 1 To 5 '假设有5行
St = St & fi.readline & vbCrLf
Next
fi.Close
Set fs = Nothing
Text1 = St
Case 2 '用FSO一次性地读入
Set fs = CreateObject("Scripting.FileSystemObject")
Set fi = fs.opentextFile(fName, 1, True)
St = fi.ReadAll
fi.Close
Set fs = Nothing
Text1 = St
Case 3 '先用InputB一次性地读入,但InputB读入的是Ansi格式,要用StrConv转成Unicode格式
Open fName For Input As #1
St = StrConv(InputB$(LOF(1), #1), vbUnicode)
Close #1
Text1 = St
Case 4 '二进制读入,一次性先读入到字节数组,经转换后再赋给Text1
fLen = FileLen(fName) - 1
ReDim DAT(fLen)
Open fName For Binary As #1
Get #1, , DAT
Close #1
Text1 = StrConv(DAT, vbUnicode)
Case 5 '二进制读入,一次性先读入到字串变量,再赋给Text1
St = Space(FileLen(fName) - 1) '先将字串变量填入文件长度的空格,这一句是必须的
Open fName For Binary As #1
Get #1, , St
Close
Text1 = St
Case 6 '二进制读入,与第4个方法相同,但读入后以16进制数据形式显示
fLen = FileLen(fName) - 1
ReDim DAT(fLen)
Open fName For Binary As #1
Get #1, , DAT
Close
For i = 0 To fLen: St = St & Right("0" & Hex(DAT(i)), 2) & " ": Next
Text1 = St
End Select
100
End Sub
On Error GoTo 100
Dim St As String, Z As String, fLen As Long, i As Long, DAT() As Byte, fs, fi
Select Case Index
Case 0 '常见的方法,一行一行地读入
Open fName For Input As #1
Do Until EOF(1)
Line Input #1, Z
St = St & Z & vbCrLf
Loop
Close #1
Text1 = St
Case 1 '用FSO一行一行地读入,要预先知道行数
Set fs = CreateObject("Scripting.FileSystemObject")
Set fi = fs.opentextFile(fName, 1)
For i = 1 To 5 '假设有5行
St = St & fi.readline & vbCrLf
Next
fi.Close
Set fs = Nothing
Text1 = St
Case 2 '用FSO一次性地读入
Set fs = CreateObject("Scripting.FileSystemObject")
Set fi = fs.opentextFile(fName, 1, True)
St = fi.ReadAll
fi.Close
Set fs = Nothing
Text1 = St
Case 3 '先用InputB一次性地读入,但InputB读入的是Ansi格式,要用StrConv转成Unicode格式
Open fName For Input As #1
St = StrConv(InputB$(LOF(1), #1), vbUnicode)
Close #1
Text1 = St
Case 4 '二进制读入,一次性先读入到字节数组,经转换后再赋给Text1
fLen = FileLen(fName) - 1
ReDim DAT(fLen)
Open fName For Binary As #1
Get #1, , DAT
Close #1
Text1 = StrConv(DAT, vbUnicode)
Case 5 '二进制读入,一次性先读入到字串变量,再赋给Text1
St = Space(FileLen(fName) - 1) '先将字串变量填入文件长度的空格,这一句是必须的
Open fName For Binary As #1
Get #1, , St
Close
Text1 = St
Case 6 '二进制读入,与第4个方法相同,但读入后以16进制数据形式显示
fLen = FileLen(fName) - 1
ReDim DAT(fLen)
Open fName For Binary As #1
Get #1, , DAT
Close
For i = 0 To fLen: St = St & Right("0" & Hex(DAT(i)), 2) & " ": Next
Text1 = St
End Select
100
End Sub