0

我的用例是通过浏览到包含要引用的数据的文件的位置来从文本文件中读取数据。文件中的数据保存在列表中。我使用arraylist来获取数据并遍历arraylist并连接每个字符串然后创建输出文件以将数据存储在单列中,如下所示

Example of a string:    
20050000    
40223120    
40006523

样品输出:

'20050000',    
'40223120',    
'40006523'    
But my code is currently displaying the output in the format:
'20050000'20050000,
'40223120'20050000,
'40006523'40006523    

请帮忙。

public List<string> list()
    {
        List<string> Get_Receiptlist = new List<string>();
        String ReceiptNo;
        openFileDialog1.ShowDialog();
        string name_of_Textfile = openFileDialog1.FileName;
        try
        {
            StreamReader sr = new StreamReader(name_of_Textfile);
            {
                while ((ReceiptNo = sr.ReadLine()) != null)
                {
                    Get_Receiptlist.Add(ReceiptNo);
                } // end while
                MessageBox.Show("Record saved in the Data list");// just for testing purpose.
            }// end StreamReader

        }
        catch (Exception err)
        {
            MessageBox.Show("Cannot read data from file");
        }
        return Get_Receiptlist;
    }
    private void button2_Click(object sender, EventArgs e)
    {
        string single_quotation = "'";
        string comma = ",";
        string paths = @"C:\Users\sample\Desktop\FileStream\Output.txt";
        if (!File.Exists(paths))
        {
            // Create a file to write to. 
            using (StreamWriter sw = File.CreateText(paths))
            {
                string[] receipt = list().ToArray();
                foreach (string rec in receipt)
                {
                    string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
                    sw.WriteLine(quoted_receipt);
                    sw.WriteLine(Environment.NewLine);
                }//foreach

                sw.Close();

                MessageBox.Show("Finish processing File");
            }//end using
        }// end if
    }
4

1 回答 1

1

在您的方法 button2_Click 中,您的循环不好:

string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
  string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
  sw.WriteLine(quoted_receipt);
  sw.WriteLine(Environment.NewLine);
}//foreach

首先,我什至不确定它的 Java ......但如果它是 Java,那么我会用这个替换这个片段:

List<String> values = list();
for (int i = 0; i < values.size(); i++)
{
  String rec = values.get(i);
  StringBuilder quoted_receipt = new StringBuilder();
  if (i > 0) 
  {
    // add comma only if the first iteration already passed
    quoted_receipt.append(comma);
  }
  quoted_receipt.append(single_quotation).append(rec).append(single_quotation);
  sw.WriteLine(quoted_receipt.toString());
  sw.WriteLine(Environment.NewLine);
}
于 2013-03-25T13:46:09.373 回答