在长单行文件上,PowerShell不在内存异常



我的问题是我必须拆分一个只有1行但很长的文件。我尝试运行 (cat $filename).split("'")但这给了我OutofMemoryException。有没有办法浏览该文件,它不会一次尝试一次加载文件,以便我可以拆分单行。作为参考,有问题的文件大小为46MB。

我在几年前也有类似的问题。假设您的单个字符串都不超过尺寸限制,这应该有效:

$InputFileName = 'C:TempTemp.txt'
$StreamReader = New-Object System.IO.StreamReader($InputFileName, [System.Text.Encoding]::ASCII)
$Queue = New-Object System.Collections.Generic.Queue[char]
[string[]]$Array = @()
while ($StreamReader.EndOfStream -ne $True)
    {
    $CurrentChar = $StreamReader.Read()
    if ($CurrentChar -eq [char]"'")
        {
        [string]$Element = ''
        while ($Queue.Count -gt 0)
            {
            $Element += $Queue.Dequeue()
            }
        $Array += $Element
        }
    else
        {
        $Queue.Enqueue($CurrentChar)
        }
    }
$StreamReader.Close()

这将创建一个首先输入(FIFO)集合,该集合排队您的角色,直到遇到'。然后将排队的字符读取到字符串中,该字符串被添加到数组中。

最新更新