VB中的打开文件操作OPEN好象只能打开比较小的文件,如果我要打开大文件并进行分割的话该怎么操作,请高手们指点指点,谢谢了。
解决方案 »
- webbrowser出现的新问题!
- 大家常去的英文网站有哪些?
- 大连发展机会(诚招vb/vb.net/java技术部长,vb,vb.net,java程序员),欢迎应届毕业生,学校学历外语年龄工作经验不限
- 关于软件国际化的问题,希望不吝赐教!
- 请问:在IE下,点击按钮后,打开word文件,有何方法实现??
- 这个括号里的那句命令是什么?
- 求教:用ASP如何访问MS SQL2000数据库?
- 大神求助!!!用VBA实现将一个Excel2007的worksheet复制到另外一个sheet,复制的内容全部为文本格式
- dbcontrols(aa)你在吗?
- 谁和我一起参加上海的 Microsoft TechEd?
- VB如何得到光标所在处的句柄!
- 请问各位在VB中怎样打包带水晶报表的程序.
前不久讨论过一个StringBuilder类,就是大文本引发速度慢的问题,估计楼主的速度原因主要出自于这里,你可以读出一行后写入数组而不是与以前的字符串相连接,这样可以加快一点速度.
如果是文本文件 建议使用 FileSystemObject
操作方便且速度快于 Open 如果是 2进制文件则使用 Open,如果考虑效率也可以使用
api readfile 并建议文件缓冲区来读取,速度比VB的Open 快很多
Bytes() As Byte
End Type '¶¨Òåʵ¼ÊÄÚ´æÊý×éType SectionedFile
Files() As FileSection
End Type '¶¨Ò帨ÖúÄÚ´æÊý×飬ÒÔ±¸À©Õ¹Ê¹ÓÃType FileInfo
OrigProjSize As Long 'Îļþ´óС
OrigFileName As String
FileCount As Integer
FileStartNum As Long
End Type '¶¨Ò廹ԭÐÅÏ¢Îļþ½á¹¹²ÎÊýPrivate Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (DestInatIon As Any, Source As Any, ByVal LENGTH As Long)Public Function ReassembleFile(TemplateFileName As String, OutPutName As String, Optional UseOldFilename As Boolean = True) As Boolean
On Error GoTo e Form1.MousePointer = 11 Dim FileInfo As FileInfo, outname As String, File As SectionedFile, m_LngLoop As Long, OpenName Dim fnum As Integer, fnum1 As Integer ReassembleFile = True fnum = FreeFile Open TemplateFileName For Binary As #fnum Get #fnum, , FileInfo Close #fnum '¶ÁÈ¡»¹Ô­ÐÅÏ¢ÎļþµÄÓйØÄÚÈÝ If UseOldFilename Then outname = FileInfo.OrigFileName Else outname = OutPutName End If 'ÊÇ·ñ×Ô¼ºÖ¸¶¨»¹Ô­ºóÎļþÃû ReDim File.Files(1) fnum1 = FreeFile Open outname For Binary As #fnum1 For m_LngLoop = 1 To FileInfo.FileCount 'ͨ¹ý»¹Ô­ÐÅÏ¢ÖмÇÔصÄÎļþ¸öÊýÈ·¶¨¶ÁÈ¡´ÎÊý
OpenName = FileInfo.OrigFileName & "." & Format((FileInfo.FileStartNum - 1 + m_LngLoop), "00££") 'µÃµ½·Ö¸îºóÉú³ÉµÄÎļþÃû³Æ¡¢Â·¾¶ fnum = FreeFile Open OpenName For Binary As #fnum Get #fnum, 1, File.Files(1) Close #fnum '¶ÁÈ¡ Put #fnum1, , File.Files(1).Bytes 'дÈë Form1.Command6.Caption = FormatPercent(m_LngLoop / FileInfo.FileCount) Form1.Command5.Caption = OpenName Next Close #fnum1 Form1.MousePointer = 0 Exit Functione: MsgBox "Îļþ²Ù×÷²úÉúÁË´íÎó:" & Err.Description, vbExclamation ReassembleFile = False Form1.MousePointer = 0End Function
fnum = FreeFile '·µ»ØµÚÒ»¸ö¿ÕÏÐͨµÀÓÃÀ´¶ÁÈ¡ Open SplitFileName For Binary As fnum 'Óöþ½øÖÆ·½Ê½´ò¿ª±»·Ö¸îÎļþ If CInt(FilesLen / Split) >= FilesLen / Split Or CInt(FilesLen / Split) = FilesLen / Split Then m_lngNumFil = CInt(FilesLen / Split) Else m_lngNumFil = CInt(FilesLen / Split) + 1 End If '¾«È·¼ÆËãÎļþ½«±»·Ö¸îµÄ¸öÊý ReDim CurrentFile.Files(1) '·ÖÅäÒ»¸öÄڴ渨ÖúÊý×é For m_LngLoop = 1 To m_lngNumFil 'Õâ¸öÑ­»·ÓÃÀ´½«Îļþ·Ö¸î£¬²¢ÇÒÉú³É·Ö¸îºóµÄÎļþ If m_LngLoop < m_lngNumFil Then 'Èç¹û²»ÊÇ×îºóÒ»´ÎÑ­»· ReDim CurrentFile.Files(1).Bytes(0 To Split - 1)' ÖØзÖÅä´óСµÈÓÚ·Ö¸î³ß´çµÄÄÚ´æÊý×é Get #fnum, , CurrentFile.Files(1).Bytes '¶ÁÈ¡µÈÓÚ·Ö¸î´óСµÄ¶þ½øÖÆÊý¾Ýµ½ÄÚ´æÊý×é Else 'Èç¹ûÊÇ×îºóÒ»´ÎÑ­»· ReDim CurrentFile.Files(1).Bytes(0 To FilesLen - ((m_lngNumFil - 1) * Split) - 1) 'ÖØзÖÅä´óСµÈÓÚÒÅÁô³¤¶ÈµÄÄÚ´æÊý×é Get #fnum, , CurrentFile.Files(1).Bytes Close #fnum '¹Ø±Õ¶ÁÈ¡ÎļþͨµÀ End If SaveName = oName & "." & Format(BeginningNumber - 1 + m_LngLoop, "00#") '¼ÆËã·Ö¸îºóµÄÎļþÃû£¬À©Õ¹ÃûΪ00£¿ fnum1 = FreeFile 'µÃµ½µÚ¶þ¸ö¿ÕÏÐͨµÀÓÃÀ´Ð´Èë Open SaveName For Binary As fnum1 Put #fnum1, 1, CurrentFile.Files(1) DoEvents Close #fnum1 'Óöþ½øÖÆ·½Ê½Ð´Èë·Ö¸îºóµÄÎļþ Form1.Command6.Caption = FormatPercent(m_LngLoop / m_lngNumFil) 'ÏÔʾ¼òµ¥µÄ½ø¶Èָʾ Form1.Command5.Caption = SaveName 'ÏÔʾÕýÔÚ²Ù×÷µÄÎļþÃû Next Dim FileInfoFile As FileInfo '¶¨Ò廹ԭÐÅÏ¢ÎļþÄÚÈÝ FileInfoFile.FileCount = m_lngNumFil '·Ö¸îºóÎļþ¸öÊý FileInfoFile.OrigFileName = oName 'Êä³öÎļþÃû FileInfoFile.OrigProjSize = FileLen(SplitFileName) '±»·Ö¸îÎļþ´óС FileInfoFile.FileStartNum = BeginningNumber '·Ö¸îºóÎļþÆðʼ±àºÅ SaveName = oName & ".HJ" '»¹Ô­ÐÅÏ¢ÎļþÃû fnum = FreeFile Open SaveName For Binary As #fnum Put #fnum, , FileInfoFile Close #fnum 'дÈ뻹ԭÐÅÏ¢Îļþ Exit FunctionCleanUp: 'Èç¹û³öÏÖ´íÎó ReturnErrorDes = Err.Description SplitFile = False '·µ»ØֵΪfalse
End Function
Dim Bytes() As Byte
Dim Bytes1() As Byte
SplitFile1 = True 'Èç¹ûÏÂÃæûÓдíÎ󣬷µ»ØÕæÖµ On Error GoTo CleanUp Dim CurrentFile As SectionedFile, m_lngNumFil As Long, m_LngLoop As Long, FilesLen As Long FilesLen = FileLen(SplitFileName) 'µÃµ½±»·Ö¸îÎļþ´óС
ReDim Bytes(FilesLen - 1)
If FilesLen <= Split + 1 Then SplitFile1 = False
ReturnErrorDes = "±»·Ö¸îÎļþ´óССÓÚ·Ö¸îºóÎļþ´óС,ÇëÖØÐÂÉèÖÃ!"
Exit Function End If
fnum = FreeFile Open SplitFileName For Binary As fnum
Get #fnum, , Bytes Close #fnum
If CInt(FilesLen / Split) >= FilesLen / Split Or CInt(FilesLen / Split) = FilesLen / Split Then
m_lngNumFil = CInt(FilesLen / Split)
Else
m_lngNumFil = CInt(FilesLen / Split) + 1
End If For m_LngLoop = 1 To m_lngNumFil
If m_LngLoop < m_lngNumFil Then
ReDim Bytes1(Split - 1)
CopyMemory Bytes1(0), Bytes((m_LngLoop - 1) * Split), Split
Else
ReDim Bytes1(FilesLen - ((m_lngNumFil - 1) * Split) - 1)
CopyMemory Bytes1(0), Bytes((m_LngLoop - 1) * Split), FilesLen - ((m_lngNumFil - 1) * Split)
End If
SaveName = oName & "." & Format(BeginningNumber - 1 + m_LngLoop, "00#")
fnum1 = FreeFile
Open SaveName For Binary As fnum1
Put #fnum1, 1, Bytes1
DoEvents
Close #fnum1
Form1.Command6.Caption = FormatPercent(m_LngLoop / m_lngNumFil)
Form1.Command5.Caption = SaveName
Next
Exit Function
CleanUp: ReturnErrorDes = Err.Description SplitFile1 = False '·µ»ØֵΪfalse
End Function
fn=freefile
dim strFile as str
dim binFile() as byte
open filename for binary as #fn
get #fn,,binFile
close #fn
strFile=cstr(binfile)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
类代码 : CFileBuff
Option Explicit'文件缓冲类,利用块读写来提高文件的读写速度Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000
Const FILE_ATTRIBUTE_NORMAL = &H80
Const CREATE_ALWAYS = 2
Const OPEN_ALWAYS = 4
Const INVALID_HANDLE_VALUE = -1
Const ERROR_HANDLE_EOF = 38Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, _
lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, _
lpNumberOfBytesRead As Long, ByVal lpOverlapped As Long) _
As LongPrivate Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As LongPrivate Declare Function WriteFile Lib "kernel32" ( _
ByVal hFile As Long, lpBuffer As Any, _
ByVal nNumberOfBytesToWrite As Long, _
lpNumberOfBytesWritten As Long, ByVal lpOverlapped As _
Long) As LongPrivate Declare Function CreateFile Lib "kernel32" _
Alias "CreateFileA" (ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile _
As Long) As LongPrivate Declare Function SetFilePointer Lib "kernel32" ( _
ByVal hFile As Long, ByVal loWord As Long, ByVal hiWord As Long, ByVal MoveMethod As Long) As LongPublic Enum enumFileSeek
FS_BEGIN
FS_CURRENT
FS_END
End Enum
Private Const MAX_FILE_BUFF As Long = 512 '定义最大的缓冲区,正好一个扇区
Private Const EOF_CHAR As Byte = 0Private m_fb(MAX_FILE_BUFF - 1) As Byte
Private m_NeedCloseFile As Boolean '是否需要Private m_Handle As Long
Private m_OffSet As Long
Private m_DirtyFlag As Boolean
Private m_LastBuff As Boolean
Private m_MaxBytes As Long
Private m_FileName As String
'按标志创建文件
Public Function Create(FileName As String) As Boolean
m_Handle = CreateFile(FileName, GENERIC_WRITE Or GENERIC_READ, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)
If m_Handle <> INVALID_HANDLE_VALUE Then '看是否正确创建了文件
m_FileName = FileName
ReadFileToBuff
Create = True
Else
Create = False
End If
End Function
'关闭文件
Public Sub CloseFile()
WriteBuffToFile
CloseHandle m_Handle
End Sub
'移动文件指针,不支持超过2 ^ 31 的位移
Public Function FSeek(Pos As Long, FS As enumFileSeek) As Boolean
Dim iPos As Long
If m_DirtyFlag = True Then WriteBuffToFile
Select Case FS
Case FS_BEGIN
If Pos < 0 Then FSeek = False
If SetFilePointer(m_Handle, Pos, 0, 0) = &HFFFFFFFF Then
FSeek = False
Else
If ReadFileToBuff = -1 Then
FSeek = False
Else
FSeek = True
End If
End If
Case FS_END
If Pos > 0 Then FSeek = False
If SetFilePointer(m_Handle, Pos, 0, 2) = &HFFFFFFFF Then
FSeek = False
Else
If ReadFileToBuff = -1 Then
FSeek = False
Else
FSeek = True
End If
End If
Case FS_CURRENT
iPos = Pos - (m_MaxBytes - m_OffSet) '计算实际的偏移位置
If SetFilePointer(m_Handle, iPos, 0, 1) = &HFFFFFFFF Then
FSeek = False
Else
If ReadFileToBuff = -1 Then
FSeek = False
Else
FSeek = True
End If
End If
End Select
End Function
'取一个字节
'返回 1 表示正确取到字符
'返回 0 表示已到文件尾,并且ch= EOF_CHAR
'返回 -1 表示取字符错误。
Public Function GetByte(ByRef ch As Byte) As Long
Dim fl As Long
If m_LastBuff = False Then
If m_OffSet = MAX_FILE_BUFF Then
fl = ReadFileToBuff
Select Case fl
Case 0
GetByte = 0
Case -1
GetByte = -1
Case Else
ch = m_fb(0)
m_OffSet = 1
GetByte = 1
End Select
Else
ch = m_fb(m_OffSet)
m_OffSet = m_OffSet + 1
GetByte = 1
End If
Else
If m_OffSet < m_MaxBytes Then
ch = m_fb(m_OffSet)
m_OffSet = m_OffSet + 1
GetByte = 1
Else
ch = EOF_CHAR
GetByte = 0
End If
End If
End Function
'写一个字节,如果正确表示1,错误为-1
Public Function PutByte(by As Byte) As Long
If m_OffSet < MAX_FILE_BUFF Then
m_fb(m_OffSet) = by
m_OffSet = m_OffSet + 1
m_DirtyFlag = True
Else '已写满一个缓冲区
WriteBuffToFile
m_fb(0) = by
m_OffSet = 1
m_DirtyFlag = True
End If
End Function
'看当前指针是否到达文件最尾端
Public Function FEof() As Boolean
If m_LastBuff = False Then
FEof = False
Else
If m_OffSet = m_MaxBytes Then
FEof = True
Else
FEof = False
End If
End If
End Function
'///////////////////////////////////////////////////////////////////////////////////////
'预读字节到缓冲区,并返回实际读到的字节,如果返回-1,则表示出错了。
Private Function ReadFileToBuff() As Long
Dim dwReadNum As Long
If ReadFile(m_Handle, m_fb(0), MAX_FILE_BUFF, dwReadNum, 0) = 0 Then
ReadFileToBuff = -1
Else
If dwReadNum <> MAX_FILE_BUFF Then
'最后一个缓冲区
m_LastBuff = True
m_MaxBytes = dwReadNum
m_OffSet = 0
m_DirtyFlag = False
ReadFileToBuff = dwReadNum
Else
m_LastBuff = False
m_MaxBytes = MAX_FILE_BUFF
m_OffSet = 0
m_DirtyFlag = False
ReadFileToBuff = MAX_FILE_BUFF
End If
End If
End Function
'写缓冲区到文件,并返回实际写的字节数
Private Function WriteBuffToFile() As Long
Dim dwWriteNum As Long
If m_OffSet = 0 Or m_DirtyFlag = False Then '如果写入数为0或者写入标志错则不写入
WriteBuffToFile = 0
Else
If WriteFile(m_Handle, m_fb(0), m_OffSet, dwWriteNum, 0) Then
WriteBuffToFile = dwWriteNum
Else
WriteBuffToFile = -1 '出错
End If
End If
m_OffSet = 0
m_DirtyFlag = False
End FunctionPrivate Sub Class_Initialize()
Dim i As Long
m_OffSet = 0
m_Handle = 0
m_DirtyFlag = False
m_FileName = ""
m_LastBuff = False
m_MaxBytes = MAX_FILE_BUFF
End SubPrivate Sub Class_Terminate()
CloseFile
End Sub
测试代码 :Form1
Option ExplicitPrivate cfb1 As CFileBuff
Private cfb2 As CFileBuff
Private fh1 As Long
Private fh2 As LongPrivate Sub Command1_Click()
Dim fn1 As String
Dim fn2 As String
Dim fn3 As String
Dim ch As Byte
Dim i As Long
Dim st1 As Single, et1 As Single
Dim st2 As Single, et2 As Single
fn1 = App.Path & "\D.DAT"
fn2 = App.Path & "\D.BAK"
fn3 = App.Path & "\D.BAK2"
st1 = Timer
Set cfb1 = New CFileBuff
Set cfb2 = New CFileBuff
If cfb1.Create(fn1) = True Then
cfb2.Create (fn2)
Do
If cfb1.GetByte(ch) = 1 Then
cfb2.PutByte ch
Else
Exit Do
End If
Loop While cfb1.FEof = False
Else
Debug.Print "Error Open File!"
End If
Set cfb1 = Nothing
Set cfb2 = Nothing
et1 = Timer
' MsgBox CStr(et1 - st1)
st2 = Timer
fh1 = FreeFile(0)
Open fn1 For Binary As fh1
fh2 = FreeFile(0)
Open fn3 For Binary As fh2
Do
Get fh1, , ch
Put fh2, , ch
Loop While EOF(fh1) = False
Close fh1
Close fh2
et2 = Timer
MsgBox CStr(et1 - st1) & " " & CStr(et2 - st2)
Debug.Print "Success!"
End Sub
Dim sFile As String
With CommonDialog1
.DialogTitle = "打開文件"
.Filter = "TXT文件(.txt)|*.txt|所有文件(*.*)|*.*"
.ShowOpen
.CancelError = False
End With
If Trim(CommonDialog1.FileName) = "" Then
MsgBox "請選擇文件", vbInformation
Exit Sub
End If
sFile = ReadFile(CommonDialog1.FileName)end sub模塊
Option ExplicitDeclare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" _
(ByVal lpFileName As String, _
lpFindFileData As WIN32_FIND_DATA _
) As Long
Declare Function FindClose Lib "kernel32" _
(ByVal hFindFile As Long _
) As Long
Declare Function FileTimeToSystemTime Lib "kernel32" _
(lpFileTime As FILETIME, _
lpSystemTime As SYSTEMTIME _
) As Long
'
Public Const FILE_ATTRIBUTE_READONLY = &H1
Public Const FILE_ATTRIBUTE_HIDDEN = &H2
Public Const FILE_ATTRIBUTE_SYSTEM = &H4
Public Const FILE_ATTRIBUTE_DIRECTORY = &H10
Public Const FILE_ATTRIBUTE_ARCHIVE = &H20
Public Const FILE_ATTRIBUTE_NORMAL = &H80
Public Const FILE_ATTRIBUTE_TEMPORARY = &H100
Public Const FILE_ATTRIBUTE_COMPRESSED = &H800
'
Type FILETIME
LowDateTime As Long
HighDateTime As Long
End Type
Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * 260 'MUST be set to 260
cAlternate As String * 14
End Type
Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
'
Public Function Findfile(ByVal xstrfilename As String) As WIN32_FIND_DATA
On Error GoTo ErrorHandler
Dim Win32Data As WIN32_FIND_DATA
Dim plngFirstFileHwnd As Long
Dim plngRtn As Long
plngFirstFileHwnd = FindFirstFile(xstrfilename, Win32Data) ' Get information of file using API call
If plngFirstFileHwnd = 0 Then
Findfile.cFileName = "Error" ' If file was not found, return error as name
Else
Findfile = Win32Data ' Else return results
End If
plngRtn = FindClose(plngFirstFileHwnd) ' It is important that you close the handle for FindFirstFile
Exit Function 'Sub
ErrorHandler: ' 'On Error GoTo ErrorHandler
Dim funName
funName = "Findfile"
' Call WriteRunErrInfo(funName, Err.Number, Err.Description)
End FunctionPublic Function ReadFile(ByVal FileAllPath As String) As String
' Dim i As Long
'FileAllPath = "d:\sb$\test.txt"
'get file size
Dim filedata As WIN32_FIND_DATA
Dim nFileSize As Long
filedata = Findfile(FileAllPath) ' Get file information
If filedata.nFileSizeHigh = 0 Then '
nFileSize = filedata.nFileSizeLow '& " Bytes"
Else
nFileSize = filedata.nFileSizeHigh '& "Bytes"
End If
If nFileSize <= 0 Then '(error 61)
Exit Function
End If
'read file:
Dim bytBuffer() As Byte
ReDim bytBuffer(nFileSize - 1)
Dim nFileNum As Integer
nFileNum = FreeFile
Open FileAllPath For Binary As #nFileNum
Get #nFileNum, , bytBuffer()
Close #nFileNum
Dim sTeleText As String
sTeleText = StrConv(bytBuffer(), vbUnicode)
ReadFile = sTeleText
End Function