2010-07-27 79 views
0

我有了> 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

小记:'ControlChars.Lf'是'Char',并且不需要转换成'Char' ... – Abel 2010-07-27 17:36:45

回答

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 
+0

原来的顺序是非常重要的。我把你的模型修改成具有相同的顺序。谢谢。 – 2010-07-27 19:39:10

0
  • 打开10的输出文件。
  • 迭代通过在输入文件中的每一行执行以下操作:
    • 斯普利特排队的行元素,然后适当地
    • 切片他们对于每一个切片,将其写入到相应的文件

中提琴。你只需要遍历oDataList一次。

+0

行和行不一样吗? – Abel 2010-07-27 17:35:47

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++]); 
     } 
    } 
} 
相关问题