2010-07-27 45 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++]); 
     } 
    } 
} 
相關問題