将数据写入文本文件 [英] Writing data to a text file

查看:76
本文介绍了将数据写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序,其中我将7个数字中的6个写入文本文件.逻辑上一切似乎都很好.

I have a simple program where I write 6 of 7 numbers to a text file. Logically everything seems to be fine.

但是数字并没有按预期写入文件.

However the numbers are not written to the file as expected.

Random random = new Random();

Console.WriteLine("Please enter the name of the numbers file");
string fileLotto = Console.ReadLine();
//creating the lotto file
FileStream fs = new FileStream("../../" + fileLotto + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
BufferedStream bs = new BufferedStream(fs);
Console.WriteLine("File created");
fs.Close();
StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt");

for(int i = 0; i < 6; i++)
{
    for(int j = 0; j < 7; j++)
    {
        //Console.Write(random.Next(1, 49));
        sw.Write(random.Next(1, 49) + " " );

    }
    sw.WriteLine();

}
sw.Close();

文件已创建,但是没有数字写入文件……关于为什么的建议?

The file was created, however no numbers were written to the file...advice perhaps as to why?

推荐答案

请注意,您的代码未经过优化,并且创建了许多不必要的流和缓冲区,但@Michael的回答概述了在此处使用的正确代码.我的答案只是强调为什么您的代码无法按预期方式工作.

Note that your code is not optimized and has a lot of unnecessary streams and buffers being created but the answer by @Michael outlines the right code to use in it's place. My answer will just highlight why your code wasn't working in the intended way.

您的问题的答案实际上非常简单.

The answer to your question is actually very simple.

StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt");

您忘记了将字符串中的/添加到 ../.. .如果假定 fileLotto 的值为 example ,则 FileStream 将创建文件 example.txt ,但 StreamWriter 将访问 .. example.txt 进行写入,并且也将其存储在其他文件夹中.

You have forgotten to add the / in the string to ../... If fileLotto is assumed to have the value example then the FileStream will create the file example.txt but the StreamWriter will access ..example.txt for writing and that too in a different folder.

使用变量定义必须重复使用的值.记住DRY原理.

Use variables to define values that have to be repeated used. Remember the DRY principle.

Random random = new Random();

Console.WriteLine("Please enter the name of the numbers file");
string fileLotto = Console.ReadLine();
string fileName = "../../" + fileLotto + ".txt";
//creating the lotto file
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
Console.WriteLine("File created");
fs.Close();

StreamWriter sw = new StreamWriter(fileName);

for(int i = 0; i < 6; i++)
{
    for(int j = 0; j < 7; j++)
    {
        //Console.Write(random.Next(1, 49));
        sw.Write(random.Next(1, 49) + " " );

    }
    Console.WriteLine();

}
sw.Close();

同样,我说请使用@Michael的代码.这只是为了突出您代码的主要问题.

Again I say please use @Michael's code. This is just to highlight the primary issue with your code.

这篇关于将数据写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆