读取和写入文本文件

读取和写入文本文件

Read a Text File 的这篇文章部分描述如何使用 StreamReader 类来读取文本的文件。Write a Text File (Example 1),和 Write a Text File (Example 2) 在各节说明了如何使用 StreamWriter 类来向文件写入文本。

读取文本文件

若要打开、 读取,和来关闭文本文件,下面的代码使用 StreamReader 类。您可以将文本文件的路径传递给 StreamReader 构造函数自动打开该文件。ReadLine 方法读取的每一行文本,并读取递增到下一行将文件指针。当 ReadLine 方法到达文件结尾时, 它将返回空引用。

  1. 在记事本中创建示例文本文件。若要这样做,请按照下列步骤操作:
    1. 在记事本中粘贴以下文本:
      hello world
    2. 将文件另存为 Sample.txt。
  2. 启动 Microsoft Visual Studio。
  3. 文件 菜单上指向 新建,然后单击 项目
  4. 项目类型 框中,单击 Visual C# 项目,然后单击 模板 下的 控制台应用程序

    注意在 Visual Studio 2005 或 Visual Studio 2008 中在 项目类型 框中,单击 Visual C#,然后单击在 模板 下的 控制台应用程序
  5. Class1.cs 文件的开头添加以下代码:
    using System.IO;
    Visual Studio 2005 或 Visual Studio 2008,默认的文件的 注释 是 Program.cs。
  6. 将下面的代码添加到 Main 方法:
    String line;try {//Pass the file path and file name to the StreamReader constructorStreamReader sr = new StreamReader("C:\\Sample.txt");//Read the first line of textline = sr.ReadLine();//Continue to read until you reach end of filewhile (line != null) {//write the lie to console windowConsole.WriteLine(line);//Read the next lineline = sr.ReadLine();}//close the filesr.Close();Console.ReadLine();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}   finally {Console.WriteLine("Executing finally block.");}
    块。
  7. 调试 菜单上单击编译并运行该应用程序,请 开始。若要关闭控制台窗口按 ENTER。控制台窗口将显示 Sample.txt 文件
    Hello world
    中的内容

写文本文件 (示例 1)

下面的代码使用 StreamWriter 类打开、 写入,和以关闭该文本文件。StreamReader 类以类似方式您可以将文本文件的路径传递给该 StreamWriter 构造函数,以自动打开该文件。WriteLine 方法写入文本文件的完整文本行。

  1. 启动 Visual Studio。
  2. 文件 菜单上指向 新建,然后单击 项目
  3. 项目类型 框中,单击 Visual C# 项目,然后单击 模板 下的 控制台应用程序

    注意 在 Visual Studio 2005 或 Visual Studio 2008 中在 项目类型 框中,单击 Visual C#,然后单击 模板 下的 CLR 控制台应用程序
  4. Class1.cs 文件的开头添加以下代码:
    using System.IO;
  5. 将下面的代码添加到 Main 方法:
    try {//Pass the filepath and filename to the StreamWriter ConstructorStreamWriter sw = new StreamWriter("C:\\Test.txt");//Write a line of textsw.WriteLine("Hello World!!");//Write a second line of textsw.WriteLine("From the StreamWriter class");//Close the filesw.Close();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}finally {Console.WriteLine("Executing finally block.");}
    块。
  6. 调试 菜单上单击编译并运行该应用程序,请 开始。此代码创建的在文本编辑器 (如记事本) 的驱动器 c。 打开 Test.txt 上名为 Test.txt 文件。 Test.txt 包含两行文字:
    Hello World!!From the StreamWriter class

写文本文件 (示例 2)

下面的代码使用 StreamWriter 类打开、 写入,和以关闭该文本文件。与前面的示例不同此代码将两个附加参数传递给构造函数。第一个参数是该文件的路径和文件的文件名。第二个参数 为 True,指定打开该文件中追加模式。如果您在第二个参数指定 False,该文件的内容将覆盖每次运行该代码。第三个参数指定 Unicode,以便 StreamWriter 对该文件以 Unicode 格式进行编码。 您还可以指定下列编码方法的第三个参数:

  • ASC11
  • Unicode
  • UTF7
  • UTF8

Write 方法是与 WriteLine 方法类似,不同之处在于 Write 方法不会自动嵌入回车或换行 (CR/LF) 字符组合。当您想要一次写入一个字符时,这是很有用。

  1. 启动 Visual Studio。
  2. 文件 菜单上指向 新建,然后单击 项目
  3. 项目类型 框中,单击 Visual C# 项目,然后单击 模板 下的 控制台应用程序

    注意在 Visual Studio 2005 或 Visual Studio 2008 单击 Visual C#项目类型,然后单击 模板 下的 控制台应用程序
  4. Class1.cs 文件的开头添加以下代码:
    using System.IO;using System.Text;
    Visual Studio 2005 或 Visual Studio 2008,默认的文件的 注释 是 Program.cs。
  5. 将下面的代码添加到 Main 方法:
    Int64 x;try {//Open the FileStreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);//Writeout the numbers 1 to 10 on the same line.for(x=0; x < 10; x++){sw.Write(x);}//close the filesw.Close();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}finally {Console.WriteLine("Executing finally block.");}
  6. 调试 菜单上单击编译并运行该应用程序,请 开始。此代码创建一个命名 Test1.txt 为驱动器 c。 打开 Test1.txt 在文本编辑器 (如记事本) 上的文件。Test1.txt 包含单行文本:
    0123456789

完成代码列表
  • 读取文本文件
    //Read a Text Fileusing System;using System.IO;namespace readwriteapp{class Class1{[STAThread]static void Main(string[] args){String line;try {//Pass the file path and file name to the StreamReader constructorStreamReader sr = new StreamReader("C:\\Sample.txt");//Read the first line of textline = sr.ReadLine();//Continue to read until you reach end of filewhile (line != null) {//write the lie to console windowConsole.WriteLine(line);//Read the next lineline = sr.ReadLine();}//close the filesr.Close();Console.ReadLine();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}finally {Console.WriteLine("Executing finally block.");}}}}
    块。
  • 写文本文件 (版本 1)
    //Write a text file - Version-1using System;using System.IO;namespace readwriteapp{class Class1{[STAThread]static void Main(string[] args) {try {//Pass the filepath and filename to the StreamWriter ConstructorStreamWriter sw = new StreamWriter("C:\\Test.txt");//Write a line of textsw.WriteLine("Hello World!!");//Write a second line of textsw.WriteLine("From the StreamWriter class");//Close the filesw.Close();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}finally {Console.WriteLine("Executing finally block.");}}}}
    块。
  • 写文本文件 (版本 2)
    //Write a text file  - Version 2using System;using System.IO;using System.Text;namespace readwriteapp{class Class1{[STAThread]static void Main(string[] args) {   Int64 x;try {//Open the FileStreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);//Writeout the numbers 1 to 10 on the same line.for(x=0; x < 10; x++){sw.Write(x);}//close the filesw.Close();}catch(Exception e){Console.WriteLine("Exception: " + e.Message);}finally {Console.WriteLine("Executing finally block.");}}}}

疑难解答

对于所有的文件操作,它是一个良好的编程习惯来包装中 一次尝试-catch-finally 程序块来处理错误和异常代码。专门,您可能希望释放最后块中文件的句柄,使该文件未被无限期锁定。一些可能的错误包括一个文件不存在或已在使用中的文件。

转载于:https://www.cnblogs.com/yanghb/archive/2010/08/24/1807022.html

JavaScript是一种热门的脚本语言,它可以通过各种方式读取文件写入文本文件。下面将详细说明如何使用JavaScript读取写入文本文件。 1. 读取文件 要在JavaScript中读取文件,可以使用File API。首先,需要创建一个input元素,该元素将用于选择要读取的文件。 ```html <input type="file" id="fileInput" /> ``` 然后,使用JavaScript获取选择的文件,并读取其内容。 ```javascript const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const reader = new FileReader(); reader.onload = function(event) { const content = event.target.result; console.log(content); // 输出文件内容 }; reader.readAsText(file); ``` 上述代码中,先获取input元素选择的文件。然后创建一个FileReader对象,并将其onload事件设置为当文件读取完成时执行的函数。最后,使用readAsText方法读取文件内容。 2. 写入文本文件 要在JavaScript中写入文本文件,可以使用BlobURL.createObjectURL方法。首先,需要创建一个包含要写入文本内容的Blob对象。 ```javascript const content = '这是要写入文件的文本内容'; const blob = new Blob([content], {type: 'text/plain'}); ``` 然后,使用URL.createObjectURL方法为Blob对象创建一个URL,将其作为链接下载或保存。 ```javascript const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'file.txt'; // 下载的文件名 link.click(); ``` 上述代码中,先创建一个a元素作为链接,并设置其href属性为Blob对象所创建的URL。然后,设置download属性为下载的文件名。最后,调用click方法触发链接点击事件,从而下载或保存文件。 总结: 通过使用File APIBlob对象,JavaScript可以读取写入文本文件读取文件时,可以使用FileReader对象读取文件的内容。写入文件时,需要创建一个包含文本内容的Blob对象,并使用URL.createObjectURL方法创建URL来下载或保存文件。以上是关于JavaScript读取写入文本文件的简单介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值