代码之家  ›  专栏  ›  技术社区  ›  Michael Wheeler

通过拆分数据将一个文件转换为十个文件

  •  0
  • Michael Wheeler  · 技术社区  · 14 年前

    我有一个文件有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?

    有没有更好的方法让他们知道我现在在做什么?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Abel    14 年前

    如果行的顺序不重要,可以执行以下操作将内容分成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
    
        2
  •  1
  •   Anthony Pegram    14 年前

    如果原始文件中的行数相对较小,则可以将它们全部读取到一行代码中的数组中。从这里,生成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++]);
            }
        }
    }
    
        3
  •  0
  •   pv2b    14 年前
    • 打开10个输出文件。
    • 循环访问输入文件中的每一行,执行以下操作:
      • 将该行的行元素拆分,然后适当地对其进行切片。
      • 对于每个切片,将其写入相应的文件

    维奥尔雅您只需要迭代一次Odalist。