vb.net 教程 4-8 文本文件读写 3

来源:互联网 发布:企业大数据架构 编辑:程序博客网 时间:2024/06/05 04:11
继续上一节,继续读写代码的编写。

为了简化操作,所有的Encoding均采用Encoding.Default。

读取方法3;
直接使用StreamReader(   参数1:要打开的文件全路径,参数2:编码格式)
读取方式:循环读取一行文本

    Private Sub readText3(ByVal filename As String)        Dim textContent As String        Dim sr As New StreamReader(filename, Encoding.Default)        Do            textContent = sr.ReadLine()            If IsNothing(textContent) Then Exit Do            txtFile.Text &= textContent & ControlChars.CrLf        Loop While True        sr.Close()    End Sub

写入方法3:
直接使用StreamWriter(参数1:文件流,参数2:不追加)
写入方式:循环每次写入一行文本,并自动在行末加上回车换行符
    Private Sub writeText3(ByVal filename As String)        Dim textContent As String = txtFile.Text        Dim sw As New StreamWriter(filename, False)        Dim arrTextContent() As String = textContent.Split(ControlChars.CrLf)        For i As Integer = 0 To arrTextContent.Length - 1            sw.WriteLine(arrTextContent(i))        Next        sw.Close()    End Sub
使用时会发现,最后多写了一个回车。因为使用split的时候最后一个ControlChars.CrLf多带来了一个空字符串。请自行改正。


读取方法4:
先使用FileStream指定打开方式打开文件并读入文件流
再使用StreamReader(参数1:文件流,参数2:编码格式)
读取方式:将文本读入字符数组,然后将字符数组还原为字符串
    Private Sub readText4(ByVal filename As String)        Dim textContent As String        Dim buffer() As Char        Dim lenRead As Long        Dim fs As New FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read)        lenRead = fs.Length        Dim sr As New StreamReader(fs, Encoding.Default)        ReDim buffer(lenRead - 1)        sr.Read(buffer, 0, lenRead)        sr.Close()        fs.Close()        textContent = New String(buffer)        txtFile.Text = textContent    End Sub


写入方法4:
先使用FileStream指定打开方式打开文件并读入文件流
再使用StreamWriter( 参数1:文件流,参数2:编码格式)
写入方式:获得流长度,向流长度大小的缓冲一次性写入所有文本
    Private Sub writeText4(ByVal filename As String)        Dim textContent As String = txtFile.Text        Dim lenWrite As Long        Dim fs As New FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)        lenWrite = textContent.Length        Dim sw As New StreamWriter(fs, Encoding.Default, lenWrite - 1)        sw.WriteLine(textContent)        sw.Close()        fs.Close()    End Sub

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看vb.net 教程 目录









原创粉丝点击