生产安全培训内容:本人写了如下代码读取一个文本文件(大约2m多),但是读取的时间太长,有没有更好的办法解决速度问题!

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/03 03:02:35
本人写了如下代码读取一个文本文件(大约2m多),但是读取的时间太长,有没有更好的办法解决速度问题!
多谢!
在线等!!

read ="D:\web\" & 文件名& "." & "txt"
Set fileSysObj = createObject("Scripting.FileSystemObject")
' 创建一个 FileSystem Object 实例,并把它保存到 fileSysObj 的变量中
IF (fileSysObj.FileExists(read)) Then
Set tf = filesysobj.OpenTextFile(read,1)
Do While not tf.AtendOfStream
' 如果文件在,就打开读取
read = tf.Readline
tempstr1 = read
tempstr = toCharArray(tempstr1)
nnn = len(tempstr1)
n =0
n1 = 0

for i = 0 to nnn
if (tempstr(i) = ",") and (n =4) then
n5 = i
n= n+1
end if
if (tempstr(i) = ",") and (n =3) then
n4 = i
n= n+1
end if
if (tempstr(i) = ",") and (n =2) then
n3 = i
n= n+1
end if
if (tempstr(i) = ",") and (n =1) then
n2 = i
n= n+1
end if

if (tempstr(i) = ",") and (n =0) then
n1 = i
n= n+1
end if
next
DayV = ""
HourV = ""
MinV = ""
DevV = ""
Value1 = ""
Value2 = ""
for i = 0 to n1-1
DayV = DayV & tempstr(i)
next
for i = n1+1 to n2-1
HourV = HourV & tempstr(i)
next
for i = n2+1 to n3-1
MinV = MinV & tempstr(i)
next
for i = n3+1 to n4-1
DevV = DevV & tempstr(i)
next
for i = n4+1 to n5-1
Value1 = Value1 & tempstr(i)
next
for i = n5+1 to nnn
Value2 = Value2 & tempstr(i)
next

d = int(DayV)
h = int(HourV)
s = int(MinV)
dev = int(DevV)

if (s = s1) and (dev = devs(0)) then
value24(TBTB*24+h) = Value1
end if

if (s = s1) and (dev = devs(1)) then
value244(TBTB*24+h) = Value1
end if
''******************************************************************
loop
tf.Close
另外本代码是asp 中的VBScript脚本
请高手们不吝赐教!!!
小的万分感激

修改内容比较多,建议:
1、判断文件长度,分块读取;使用字符串存储读取内容,减少文件操作。(不改也可)。
2、《主要》:使用数组代替n1、n2、n3、n4、n5,当第五个读取完成后退出For循环,减少循环次数;你的程序可判断可以改成下面这样,再试一下运行速度:

'--------前面的不变,从循环开始--------
Index=0
Dim X(1 to 5) As Long
For i = 0 To nnn
If (tempstr(i) = ",") Then
X(Index) = i
Index = Iindex + 1
If Index>5 Then Exit For
End If
Next
DayV = ""
HourV = ""
MinV = ""
DevV = ""
Value1 = ""
Value2 = ""
Dim MyStr As String,M As Long,N As Long
Index = 1:Gosub GetData:DayV = MyStr
Index = 2:Gosub GetData:HourV = MyStr
Index = 3:Gosub GetData:DevV = MyStr
Index = 4:Gosub GetData:Value1 = MyStr
Index = 5:Gosub GetData:Value2 = MyStr
Goto N1

GetData:
MyStr = ""
If Index=1 Then
M = 0
Else
M = X(Index) + 1
Endif
If Index = 5 Then
N = nnn
Else
N = X(Index+1) - 1
End If
For i = M To N
MyStr = MyStr & & tempstr(i)
Next
Return

N1:
'--------后面的不变--------
d = int(DayV)
h = int(HourV)
s = int(MinV)
dev = int(DevV)
if (s = s1) and (dev = devs(0)) then
value24(TBTB*24+h) = Value1
end if

if (s = s1) and (dev = devs(1)) then
value244(TBTB*24+h) = Value1
end if
''******************************************************************
loop
tf.Close

VB我不是很通. 我是搞别的语言的. 但如果文件大的话, 你一行一行地读肯定是慢的. 应该成块地读, 然后在内存中处理. 当然这样程序比较复杂, 因为要分析字符串, 但肯定要比你这样快. 但我不知道VB中有没有成块读取文件的函数.