我试图使用流读取器/写入器来避免占用内存,因为其中一些文件超过 300MB。我找不到完全避免内存的方法,但我没有将文件放入内存,而是创建了一个介于 0 和 Total Lines 之间的随机数字数组。该数组指示将哪些行放入示例文件中。
为数据创建流阅读器
$reader = New-Object -TypeName System.IO.StreamReader("data.txt");
为测试群体创建流编写器
$writer_stream = New-Object -TypeName System.IO.FileStream(
("test_population.txt"),
[System.IO.FileMode]::Create,
[System.IO.FileAccess]::Write);
$writer= New-Object -TypeName System.IO.StreamWriter(
$writer_stream,
[System.Text.Encoding]::ASCII);
为控制组创建 Stream Writer
$writer_stream_control = New-Object -TypeName System.IO.FileStream(
("control.txt"),
[System.IO.FileMode]::Create,
[System.IO.FileAccess]::Write);
$writer_control= New-Object -TypeName System.IO.StreamWriter(
$writer_stream_control,
[System.Text.Encoding]::ASCII);
确定控件大小并随机选择介于 0 和文件总行数之间的数字。
$line_count = 10000000
$control_percent = 0.15
$control_size = [math]::round($control_percent*$line_count)
创建一个随机数索引以确定哪些行应该进入示例文件。确保在最后通过排序管道。
$idx = Get-Random -count $control_size -InputObject(0..($line_count-1))|sort -Unique
将 $i 表示为行号;使用 $idx[$j] 作为应该转到示例文件的行
$i = 0; $j = 0
while ($reader.Peek() -ge 0) {
$line = $reader.ReadLine() #Read Line
if ($idx[$j] -eq $i){
$writer_control.WriteLine($OutPut)
$j++
}
else{$writer.WriteLine($OutPut)}
}
$i++
$reader.Close();
$reader.Dispose();
$writer.Flush();
$writer.Close();
$writer.Dispose();
$writer_control.Flush();
$writer_control.Close();
$writer_control.Dispose();