2

我正忙于一个应用程序,它读取大小从 5mb 到 1gb+ 的空间分隔日志文件,然后将此信息存储到 MySQL 数据库中,以供以后根据文件中包含的信息打印报告时使用。我尝试过/发现的方法有效,但速度很慢。

难道我做错了什么?还是有更好的方法来处理非常大的文本文件?

我尝试使用 textfieldparser 如下:

Using parser As New TextFieldParser("C:\logfiles\testfile.txt")
    parser.TextFieldType = FieldType.Delimited
    parser.CommentTokens = New String() {"#"}
    parser.Delimiters = New String() {" "}
    parser.HasFieldsEnclosedInQuotes = False
    parser.TrimWhiteSpace = True
    While Not parser.EndOfData
        Dim input As String() = parser.ReadFields()
        If input.Length = 10 Then
            'add this to a datatable
        End If
    End While
End Using

这有效,但对于较大的文件非常慢。

然后,我尝试根据以下函数使用与文本文件的 OleDB 连接以及我事先写入目录的 schema.ini 文件:

Function GetSquidData(ByVal logfile_path As String) As System.Data.DataTable
    Dim myData As New DataSet
    Dim strFilePath As String = ""
    If logfile_path.EndsWith("\") Then
        strFilePath = logfile_path
    Else
        strFilePath = logfile_path & "\"
    End If
    Dim mySelectQry As String = "SELECT * FROM testfile.txt WHERE Client_IP <> """""
    Dim myConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilePath & ";Extended Properties=""text;HDR=NO;""")
        Dim dsCmd As New System.Data.OleDb.OleDbDataAdapter(mySelectQry, myConnection)
        dsCmd.Fill(myData, "logdata")
        If Not myConnection.State = ConnectionState.Closed Then
            myConnection.Close()
        End If
    Return myData.Tables("logdata")
End Function

schema.ini 文件:

[testfile.txt]
Format=Delimited( )
ColNameHeader=False
Col1=Timestamp text
Col2=Elapsed text
Col3=Client_IP text
Col4=Action_Code text
Col5=Size double
Col6=Method text
Col7=URI text
Col8=Ident text
Col9=Hierarchy_From text
Col10=Content text

任何人都知道如何更快地读取这些文件?

-edit- 更正了上面代码中的一个错字

4

2 回答 2

2

那里有两个可能很慢的操作:

  • 文件读取
  • 向数据库中插入大量数据

将它们分开并测试最耗时的。即编写一个简单地读取文件的测试程序,和另一个只插入大量记录的测试程序。看看哪个最慢。

一个问题可能是您正在将整个文件读入内存?

尝试使用 Stream 逐行阅读。这是从 MSDN 复制的代码示例

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            ' The using statement also closes the StreamReader.
            Using sr As New StreamReader("TestFile.txt")
                Dim line As String
                ' Read and display lines from the file until the end of
                ' the file is reached.
                Do
                    line = sr.ReadLine()
                    If Not (line Is Nothing) Then
                        Console.WriteLine(line)
                    End If
                Loop Until line Is Nothing
            End Using
        Catch e As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Class
于 2011-11-24T08:58:52.890 回答
-2

从我的头顶上说,尝试使用某种线程来分散工作量。

于 2011-11-23T14:10:12.117 回答