![]() 有两种主要的文档处理类型: 创建、添加或删除数据,连同读取文档 移动、复制和删除文档 创建文档 创建空文本文档(有时被叫做“文本流”)有三种方法。 第一种方法是用 CreateTextFile 方法。 下面的示例示范了在 VBScript 中怎样用这种方法来创建文本文档: Dim fso, f1 Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.CreateTextFile("c:\testfile.txt", True) 要在 JScript 中用这种方法,则使用下面的代码: var fso, f1; fso = new ActiveXObject("Scripting.FileSystemObject"); f1 = fso.CreateTextFile("c:\\testfile.txt", true); 创建文本文档的第二种方法是,使用 FileSystemObject 对象的 OpenTextFile 方法,并配置 ForWriting 标志。在 VBScript 中,代码就像下面的示例相同: Dim fso, ts Const ForWriting = 2 Set fso = CreateObject("Scripting. FileSystemObject") Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True) 要在 JScript 中使用这种方法来创建文本文档,则使用下面的代码: var fso, ts; var ForWriting= 2; fso = new ActiveXObject("Scripting.FileSystemObject"); ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true); 创建文本文档的第三种方法是,使用 OpenAsTextStream 方法,并配置 ForWriting 标志。要使用这种方法,在 VBScript 中使用下面的代码: Dim fso, f1, ts Const ForWriting = 2 Set fso = CreateObject("Scripting.FileSystemObject") fso.CreateTextFile ("c:\test1.txt") Set f1 = fso.GetFile("c:\test1.txt") Set ts = f1.OpenAsTextStream(ForWriting, True) 在 JScript 中,则使用下面示例中的代码: var fso, f1, ts; var ForWriting = 2; fso = new ActiveXObject("Scripting.FileSystemObject"); fso.CreateTextFile ("c:\\test1.txt"); f1 = fso.GetFile("c:\\test1.txt"); ts = f1.OpenAsTextStream(ForWriting, true); 添加数据到文档中 一旦创建了文本文档,使用下面的三个步骤向文档添加数据: 打开文本文档。 写入数据。 关闭文档。 要打开现有的文档,则使用 FileSystemObject 对象的 OpenTextFile 方法或 File 对象的 OpenAsTextStream 方法。 要写数据到打开的文本文档,则根据下表所述任务使用 TextStream 对象的 Write、WriteLine 或 WriteBlankLines 方法。 任务 方法 向打开的文本文档写数据,不用后续一个新行字符。 Write 向打开的文本文档写数据,后续一个新行字符。 WriteLine 向打开的文本文档写一个或多个空白行。 WriteBlankLines 要关闭一个打开的文档,则使用 TextStream 对象的 Close 方法。 注意 新行字符包含一个或几个字符(取决于操作系统),以把光标移动到下一行的开始位置(回车/换行)。注意某些字符串末尾可能已有这个非打印字符了。 下面的 VBScript 例子示范了怎样打开文档,和同时使用三种写方法来向文档添加数据,然后关闭文档: Sub CreateFile() Dim fso, tf Set fso = CreateObject("Scripting.FileSystemObject") Set tf = fso.CreateTextFile("c:\testfile.txt", True) ’ 写一行,并且带有新行字符。 tf.WriteLine("Testing 1, 2, 3.") ’ 向文档写三个新行字符。 tf.WriteBlankLines(3) ’ 写一行。 tf.Write ("This is a test.") tf.Close End Sub 这个示例示范了在 JScript 中怎样使用这三个方法: function CreateFile() { var fso, tf; fso = new ActiveXObject("Scripting.FileSystemObject"); tf = fso.CreateTextFile("c:\\testfile.txt", true); // 写一行,并且带有新行字符。 tf.WriteLine("Testing 1, 2, 3.") ; // 向文档写三个新行字符。 tf.WriteBlankLines(3) ; // 写一行。 tf.Write ("This is a test."); tf.Close(); } |
喜欢本文,那就收藏到: |