VisualBasic实用教程 薛亮 第9章.pptVIP

  • 3
  • 0
  • 约1.22万字
  • 约 79页
  • 2017-02-28 发布于湖北
  • 举报
9.3.3 访问文件 通过FSO对象,在Visual Basic中就可以直接操作文件,而且不考虑文件类型就可以移动、复制和删除文件。 文件的操作主要有两类: (1) 创建、移动、复制和删除文件。 (2) 添加、移动数据和阅读文件。 1.用FileSystemObject创建文件并添加数据 文本文件一经创建,就可以向其中加入数据。 (1) 打开文本文件以备写入数据,使用FSO对象模型有两种创建文本文件的方法。 ① 使用CreateTextFile方法: Dim fso As New FileSystemObject, fil As File Set fil = fso.CreateTextFile(c:\testfile.txt, True) 创建一个空文本文件 ② 使用OpenTextFile方法 Dim fso As New FileSystemObject, ts As New TextStream Set ts = fso.OpenTextFile(c:\test.txt, ForWriting) (2) 打开已有文件也有下面两种方法: ① FileSystemObject对象的OpenTextFile方法。 ② File对象的OpenAsTextStream方法。 Dim fso As New FileSystemObject, fil As File, ts As TextStream Set fso = CreateObject(Scripting.FileSystemObject) fso.CreateTextFile (test1.txt) Set fil = fso.GetFile(test1.txt) Set ts = fil.OpenAsTextStream(ForWriting) (3) 写入数据。向打开的文本文件中写入数据,可以使用TextStream对象的Write或WriteLine方法。它们之间的惟一差别是WriteLine在指定的字符串末尾添加换行符。 (4) 关闭文件使用TextStream对象的方法Close( )。 【例9-5】 文件对象操作示例。 ?Sub create_file( ) Dim fso, txtfile Set fso = CreateObject(Scripting.FileSystemObject) Set txtfile = fso.CreateTextFile(c:\testfile.txt, True) 写入一行 txtfile.Write (This is a test) 写入带有换行的文本 txtfile.WriteLine (Testing 1 2 3) 写入三个换行符 txtfile.WriteBlankLines (3) txtfile.Close End Sub 2.使用FileSystemObject读取文件 从一个文本文件中读取数据,可使用TextStream对象的Read、ReadLine或ReadAll方法,其差别如表9.3所示。 表9.3 TextStream对象的读方法 【例9-6】 读取文件的实例。 Sub Read_file( ) Dim fso As New FileSystemObject, txtfile, fill As File, ts As TextStream Set txtfile = fso.CreateTextFile(c:\testfile.txt, True) MsgBox 正在写入文件 写入一行 Set fill = fso.GetFile(c:\testfile.txt) Set ts = fill.openAsTextStream(ForWriting) ts.Write Hello World ts.Close 读取文件内容 Set ts = fill.OpenAsTextStream(ForReading) s = ts.ReadLine MsgBox s ts.Close End Sub 3. 移动、复制和删除文件 对于文件的移动、复制和删除,FSO对象模型提供了两种方法,如表9.4所示。 表9.4 文件的移动、复制和删除方法 【例9-7】 在C盘的根目录下创建了一个文本文件,并向其中写入一些信息,然后将该文件移至一

文档评论(0)

1亿VIP精品文档

相关文档