首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理大文件

处理大文件
EN

Stack Overflow用户
提问于 2012-06-25 04:28:31
回答 1查看 185关注 0票数 1

我有一个很大的日志文件,需要在Windows8上使用F#进行解析。服务器一直在运行,它会通过添加新行来写入日志文件的末尾。每分钟检查一次日志文件的更改。与其重新解析整个文件,我宁愿只从末尾读取,并将新添加的行与上一次解析的结果组合在一起。更好的是,每当文件发生变化时,我都希望能够注册一个回调。这有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2013-10-27 23:44:13

你可以通过文件流Seek()来做到这一点。如下所示:

代码语言:javascript
复制
open System.IO

let WatchLog directory file =
    // Keep track of last read position
    let lastRead = ref 0L

    // Function that's called whenever the file changes
    let processLog (e : FileSystemEventArgs) =
        // Open file, and seek to the last read location
        use fs = new FileStream(Path.Combine(directory, file), FileMode.Open, FileAccess.Read)
        fs.Seek(!lastRead, SeekOrigin.Begin) |> ignore

        // Read the rest of the file
        use sr = new StreamReader(fs)
        printfn "Reading log: %A" (sr.ReadToEnd())

        // Store the length so that we know how much to seek over next time
        lastRead := fs.Length
        ()

    // Create a FS watched to be notified when a file changes
    let fs = new FileSystemWatcher(directory, file)
    fs.Changed.Add(processLog)
    fs.EnableRaisingEvents <- true

WatchLog "M:\Coding\" "TestLog.txt"

然而,由于某些原因,在我的机器上,我得到了“进程无法访问文件,因为它正被另一个进程使用”的错误,我无法跟踪它。当use语句超出作用域时,它们应该被处理,甚至对Close的显式调用也不能解决这个问题:/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11180971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档