我的文件有> 10行。我想创建9个文件,每个文件包含相同的数字或行,第10个文件包含相同的数字加上任何剩余的文件。
我目前通过以下方式从主文件中获取数据:
Dim sData As String
Using sr As New StreamReader(vsFilePath)
sData = sr.ReadToEnd
End Using
Dim oDataList As New List(Of String)
oDataList.AddRange(sData.Split(Convert.ToChar(ControlChars.Lf)))
如何获取oDataList并将其解析为10个文件而不必遍历每个文件而oDataList逐行写入?
他们目前正在做的更好的方式吗?
答案 0 :(得分:1)
如果行的顺序不重要,您可以执行以下操作以将内容分成10个相等的部分,否则,通过数据进行双循环(一个用于计数和存储行,另一个用于写入行)可能是必要的。
Dim sData As String
Dim counter As Integer
Dim sw(10) As StreamWriter
For i As Integer = 0 To 9 Step 1
sw(i) = New StreamWriter("path" + something)
Next
Using sr As New StreamReader("path")
sData = sr.ReadLine()
While sData IsNot Nothing
sw(1 Mod counter).WriteLine(sData)
counter += 1
sData = sr.ReadLine
End While
End Using
'add a finally block for closing the 10 streams
答案 1 :(得分:1)
如果原始文件中的行数相对较小,则可以将它们全部读入一行代码中的数组中。从那里,生成10个输出文件是一个简单的操作。这是一种这样的方法。
Dim path As String = "C:\Temp\test\input.txt"
Dim outputPath As String = "C:\Temp\test\output{0}.txt"
Dim lines As String() = File.ReadAllLines(path)
Dim files As Integer = 10
Dim linesPerFile As Integer = lines.Length \ 10
Dim currentLine As Integer = 0
For i As Integer = 0 To files - 1
Dim iterations As Integer = linesPerFile
If i = files - 1 Then
iterations = lines.Length - currentLine
End If
Using writer As New StreamWriter(String.Format(outputPath, i))
For j As Integer = 0 To iterations - 1
writer.WriteLine(lines(currentLine))
currentLine += 1
Next
End Using
Next
...
string path = @"C:\Temp\test\input.txt";
string outputPath = @"C:\Temp\test\output{0}.txt";
string[] lines = File.ReadAllLines(path);
int files = 10;
int linesPerFile = lines.Length / 10;
int currentLine = 0;
for (int i = 0; i < files; ++i)
{
int iterations = linesPerFile;
if (i == files - 1)
{
iterations = lines.Length - currentLine;
}
using (StreamWriter writer = new StreamWriter(string.Format(outputPath, i)))
{
for (int j = 0; j < iterations; j++)
{
writer.WriteLine(lines[currentLine++]);
}
}
}
答案 2 :(得分:0)
中提琴。您只需要遍历oDataList一次。